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

export const PUT = 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 body = await req.json();
    const { action, trialDays, planId } = body as {
      action?: 'grant_trial' | 'revoke_trial';
      trialDays?: number;
      planId?: string;
    };
    if (action && !['grant_trial', 'revoke_trial'].includes(action)) {
      throw new ValidationError('Invalid action. Must be grant_trial or revoke_trial.');
    }
    if (!action && !planId) {
      throw new ValidationError('Must provide action or planId.');
    }
    await updateRestaurantSubscription(id, { action, trialDays, planId });
    return NextResponse.json({ success: true });
  })
);
