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

export const PATCH = 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().catch(() => null) as Record<string, unknown> | null;
    if (!body || typeof body !== 'object') throw new ValidationError('Invalid request body');
    const { status } = body as { status?: string };
    if (status !== 'active' && status !== 'suspended') {
      throw new ValidationError('status must be "active" or "suspended"');
    }
    try {
      await setRestaurantStatus(id, status);
    } catch (e: unknown) {
      if (e instanceof Error && e.message === 'Restaurant not found') throw new NotFoundError('Restaurant not found');
      throw e;
    }
    return NextResponse.json({ success: true });
  })
);
