import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { createBranchSchema } from '@server/validators/branches.validator';
import { listBranches, createBranch } from '@server/services/branches.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId } = req.session;
    const url = new URL(req.url);
    const activeOnly = url.searchParams.get('active') === 'true';
    const branches = await listBranches(restaurantId!, activeOnly);
    return NextResponse.json({ branches });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createBranchSchema, async (req) => {
      const branch = await createBranch(req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ branch }, { status: 201 });
    })
  )
);
