import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError } from '@server/errors';
import {
  getAdminBillingPlansAll,
  createAdminBillingPlan,
  createAuditLog,
} from '@server/services/admin.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    if (req.session.role !== 'superadmin' && req.session.role !== 'support') {
      throw new ForbiddenError();
    }
    const plans = await getAdminBillingPlansAll();
    return NextResponse.json({ plans });
  })
);

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    if (req.session.role !== 'superadmin') {
      throw new ForbiddenError();
    }
    const body = await req.json();
    const result = await createAdminBillingPlan({
      name: body.name,
      description: body.description,
      priceMonthly: parseFloat(body.priceMonthly) || 0,
      priceAnnual: parseFloat(body.priceAnnual) || 0,
      trialDays: (() => { const v = parseInt(body.trialDays, 10); return isNaN(v) ? 0 : v; })(),
      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.created',
      resource: 'plans',
      resourceId: result.id as unknown as string,
      severity: 'info',
      metadata: { planName: body.name, stripeSkipped: result.stripeSkipped },
    });
    return NextResponse.json({ id: result.id, stripeSkipped: result.stripeSkipped }, { status: 201 });
  })
);
