import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError } from '@server/errors';
import { getPlanPrices, upsertPlanPrice } from '@server/services/billing.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 prices = await getPlanPrices(id);
    return NextResponse.json({ prices });
  })
);

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 { currencyCode, priceMonthly, priceAnnual } = body;
    if (!currencyCode) {
      return NextResponse.json({ error: 'currencyCode is required' }, { status: 400 });
    }
    await upsertPlanPrice(id, currencyCode, parseFloat(priceMonthly) || 0, parseFloat(priceAnnual) || 0);
    return NextResponse.json({ ok: true });
  })
);
