import { Router } from 'express';
import { prisma } from '../config/database.js';
import { authenticate } from '../middleware/auth.js';

const router = Router();

// GET /api/subscriptions/current
router.get('/current', authenticate, async (req, res, next) => {
  try {
    const subscription = await prisma.subscription.findUnique({
      where: { userId: req.userId! },
    });

    res.json(subscription || { tier: 'BASIC', status: 'ACTIVE', userId: req.userId });
  } catch (error) {
    next(error);
  }
});

// POST /api/subscriptions/create
router.post('/create', authenticate, async (req, res, next) => {
  try {
    const { tier } = req.body;
    if (!tier || !['PRO', 'BUSINESS'].includes(tier)) {
      res.status(400).json({ message: 'Invalid tier' });
      return;
    }

    const existing = await prisma.subscription.findUnique({ where: { userId: req.userId! } });
    if (existing && existing.status === 'ACTIVE' && existing.tier !== 'BASIC') {
      res.status(400).json({ message: 'Already have an active subscription' });
      return;
    }

    const subscription = await prisma.subscription.upsert({
      where: { userId: req.userId! },
      update: {
        tier,
        status: 'ACTIVE',
        currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
      },
      create: {
        userId: req.userId!,
        tier,
        status: 'ACTIVE',
        currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
      },
    });

    res.json(subscription);
  } catch (error) {
    next(error);
  }
});

// POST /api/subscriptions/cancel
router.post('/cancel', authenticate, async (req, res, next) => {
  try {
    const subscription = await prisma.subscription.findUnique({ where: { userId: req.userId! } });
    if (!subscription) {
      res.status(404).json({ message: 'No subscription found' });
      return;
    }

    const updated = await prisma.subscription.update({
      where: { userId: req.userId! },
      data: { status: 'CANCELLED' },
    });

    res.json(updated);
  } catch (error) {
    next(error);
  }
});

export default router;
