import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { branchAvailabilitySchema } from '@server/validators/menu.validator';
import { upsertBranchAvailability, deleteBranchAvailability } from '@server/services/menu.service';
import { assertBranchAccess } from '@server/utils/branch-access';

// Pinned-branch operators may only mutate availability for their own branch.
// Owners (no pinnedBranchId) may mutate any branch in the restaurant.
export const PUT = withErrorHandler(
  withAuth(
    withValidationAuthed(branchAvailabilitySchema, async (req, ctx: RouteContext) => {
      const { id, branchId } = await ctx.params;
      assertBranchAccess(req.session, branchId);
      const body = req.parsedBody as { is_available: boolean };
      const row = await upsertBranchAvailability(
        id,
        branchId,
        req.session.restaurantId!,
        body.is_available,
        { userId: req.session.userId, email: req.session.email },
      );
      return NextResponse.json({ override: row });
    })
  )
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id, branchId } = await ctx.params;
    assertBranchAccess(req.session, branchId);
    await deleteBranchAvailability(id, branchId, req.session.restaurantId!, {
      userId: req.session.userId,
      email: req.session.email,
    });
    return NextResponse.json({ success: true });
  })
);
