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

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    if (req.session.role !== 'superadmin' && req.session.role !== 'support') {
      throw new ForbiddenError();
    }
    const restaurants = await getAdminRestaurantList();
    return NextResponse.json({ restaurants });
  })
);

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    if (req.session.role !== 'superadmin') {
      throw new ForbiddenError();
    }
    const body = await req.json();
    const { restaurantName, ownerName, ownerEmail, ownerPassword, plan } = body;

    if (!restaurantName?.trim()) throw new ValidationError('Restaurant name is required');
    if (!ownerEmail?.trim()) throw new ValidationError('Owner email is required');
    if (ownerPassword && ownerPassword.length < 8) throw new ValidationError('Password must be at least 8 characters if provided');

    try {
      const result = await createAdminRestaurant({
        restaurantName,
        ownerName: ownerName ?? '',
        ownerEmail,
        ownerPassword,
        plan: plan ?? 'starter',
        adminActorEmail: req.session.email,
      });
      return NextResponse.json({ success: true, restaurant: result }, { status: 201 });
    } catch (err: unknown) {
      if (err instanceof Error && err.message.includes('already exists')) {
        throw new ConflictError(err.message);
      }
      throw err;
    }
  })
);
