import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError, NotFoundError } from '@server/errors';
import {
  getAdminBillingPlanById,
  updateAdminBillingPlan,
  deleteAdminBillingPlan,
  createAuditLog,
} from '@server/services/admin.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, context: { params: Promise<Record<string, string>> }) => {
    if (req.session.role !== 'superadmin' && req.session.role !== 'support') {
      throw new ForbiddenError();
    }
    const { id } = await context.params;
    const plan = await getAdminBillingPlanById(id);
    if (!plan) throw new NotFoundError('Plan not found');
    return NextResponse.json({ plan });
  })
);

export const PUT = withErrorHandler(
  withAuth(async (req: AuthedRequest, context: { params: Promise<Record<string, string>> }) => {
    if (req.session.role !== 'superadmin') {
      throw new ForbiddenError();
    }
    const { id } = await context.params;
    const body = await req.json();
    const result = await updateAdminBillingPlan(id, {
      name: body.name,
      description: body.description,
      priceMonthly: parseFloat(body.priceMonthly) || 0,
      priceAnnual: parseFloat(body.priceAnnual) || 0,
      trialDays: parseInt(body.trialDays, 10) || 14,
      features: body.features ?? [],
      limits: body.limits ?? {},
      isActive: body.isActive !== false,
    });
    await createAuditLog({
      actorId: req.session.userId,
      actorEmail: req.session.email,
      actorType: 'admin',
      action: 'billing_plan.updated',
      resource: 'plans',
      resourceId: id as unknown as string,
      severity: 'info',
      metadata: { planName: body.name, stripeSkipped: result.stripeSkipped },
    });
    return NextResponse.json({ ok: true, stripeSkipped: result.stripeSkipped });
  })
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, context: { params: Promise<Record<string, string>> }) => {
    if (req.session.role !== 'superadmin') {
      throw new ForbiddenError();
    }
    const { id } = await context.params;
    await deleteAdminBillingPlan(id);
    await createAuditLog({
      actorId: req.session.userId,
      actorEmail: req.session.email,
      actorType: 'admin',
      action: 'billing_plan.deleted',
      resource: 'plans',
      resourceId: id as unknown as string,
      severity: 'warning',
    });
    return NextResponse.json({ ok: true });
  })
);
