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');
    const { getStripeSecretKey } = await import('@server/lib/stripe');
    const stripeConfigured = Boolean(await getStripeSecretKey());
    const stripeStatus = result.stripeStatus ?? (!stripeConfigured ? 'not_configured' : 'not_synced');

    const { getRazorpayCredentials } = await import('@server/lib/razorpay');
    const razorpayCreds = await getRazorpayCredentials();
    const razorpayConfigured = Boolean(razorpayCreds);
    const razorpayStatus = !razorpayConfigured ? 'not_configured'
      : result.razorpaySkipped ? 'not_synced'
      : 'synced';

    await createAuditLog({
      actorId: req.session.userId,
      actorEmail: req.session.email,
      actorType: 'admin',
      action: 'billing_plan.sync',
      resource: 'plans',
      resourceId: id,
      severity: 'info',
      metadata: { stripeSkipped: result.stripeSkipped, stripeStatus, razorpaySkipped: result.razorpaySkipped, razorpayStatus },
    });
    return NextResponse.json({
      ok: true,
      stripeStatus,
      stripeSkipped: result.stripeSkipped,
      razorpayStatus,
      razorpaySkipped: result.razorpaySkipped,
    });
  })
);
