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

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    if (req.session.role !== 'superadmin' && req.session.role !== 'support') {
      throw new ForbiddenError();
    }
    const url = new URL(req.url);
    const restaurantId = url.searchParams.get('restaurant_id');
    if (!restaurantId) throw new ValidationError('restaurant_id is required');
    const branches = await listBranches(restaurantId);
    return NextResponse.json({ branches });
  })
);
