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 { updateBranchSchema } from '@server/validators/branches.validator';
import { getBranch, updateBranch, deleteBranch } from '@server/services/branches.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    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;
      const branch = await updateBranch(id, req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ branch });
    })
  )
);

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