import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, requireSectionAny, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { updateBranchSchema } from '@server/validators/branches.validator';
import { getBranch, updateBranch, deleteBranch } from '@server/services/branches.service';
import { requirePlanFeature } from '@server/utils/features';
import { assertBranchAccess, requireOwner } from '@server/utils/branch-access';

const STOREFRONT_FIELDS = new Set([
  'storefront_enabled',
  'accepts_dine_in',
  'accepts_takeaway',
  'accepts_delivery',
  'min_order_value',
  'storefront_message',
  'qr_style_json',
  'slug',
]);

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    assertBranchAccess(req.session, id);
    await requireSectionAny(req, ['branches', 'storefront', 'telephone']);
    const branch = await getBranch(id, req.session.restaurantId!);
    return NextResponse.json({ branch });
  })
);

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateBranchSchema, async (req, ctx: RouteContext) => {
      const { id } = await ctx.params;
      assertBranchAccess(req.session, id);
      await requireSectionAny(req, ['branches', 'storefront'], 'update');
      const body = req.parsedBody as Record<string, unknown>;
      if (Object.keys(body).some((k) => STOREFRONT_FIELDS.has(k))) {
        await requirePlanFeature(req.session.restaurantId!, 'storefront');
      }
      const branch = await updateBranch(id, req.session.restaurantId!, body);
      return NextResponse.json({ branch });
    })
  )
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    requireOwner(req.session, 'delete branches');
    await deleteBranch(id, req.session.restaurantId!);
    return NextResponse.json({ success: true });
  })
);
