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

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 detail = await getAdminRestaurantDetail(id);
    if (!detail) throw new NotFoundError('Restaurant not found');
    return NextResponse.json({ restaurant: detail });
  })
);

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 name = typeof body.name === 'string' && body.name.trim() ? body.name.trim() : undefined;
    const phone = body.phone !== undefined ? (typeof body.phone === 'string' && body.phone.trim() ? body.phone.trim() : null) : undefined;
    const cuisineType = body.cuisineType !== undefined ? (typeof body.cuisineType === 'string' && body.cuisineType.trim() ? body.cuisineType.trim() : null) : undefined;
    const address = body.address !== undefined ? (typeof body.address === 'string' && body.address.trim() ? body.address.trim() : null) : undefined;
    const seatingCapacity = body.seatingCapacity !== undefined
      ? (body.seatingCapacity === null ? null : (Number.isFinite(Number(body.seatingCapacity)) ? Number(body.seatingCapacity) : null))
      : undefined;
    try {
      await updateRestaurantProfile(id, { name, phone, cuisineType, address, seatingCapacity });
    } 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 });
  })
);
