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 {
  syncAdminBillingPlan,
  createAuditLog,
} from '@server/services/admin.service';

export const POST = 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 result = await syncAdminBillingPlan(id);
    if (result === null) throw new NotFoundError('Plan not found');
    await createAuditLog({
      actorId: req.session.userId,
      actorEmail: req.session.email,
      actorType: 'admin',
      action: 'billing_plan.stripe_sync',
      resource: 'plans',
      resourceId: id,
      severity: 'info',
      metadata: { stripeSkipped: result.stripeSkipped, stripeStatus: result.stripeStatus },
    });
    return NextResponse.json({ ok: true, stripeStatus: result.stripeStatus, stripeSkipped: result.stripeSkipped });
  })
);
