import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { switchBranchSchema, type SwitchBranchInput } from '@server/validators/branches.validator';
import { createSession, COOKIE_NAME } from '@server/auth';
import { getBranch } from '@server/services/branches.service';
import { ValidationError } from '@server/errors';

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(switchBranchSchema, async (req) => {
      const { branchId } = req.parsedBody as SwitchBranchInput;
      const { session } = req;

      if (!session.restaurantId) throw new ValidationError('No restaurant in session');

      const branch = await getBranch(branchId, session.restaurantId);
      if (!branch.is_active) throw new ValidationError('Cannot switch to an inactive branch');

      const newToken = await createSession({ ...session, branchId });

      const res = NextResponse.json({ ok: true });
      res.cookies.set(COOKIE_NAME, newToken, {
        httpOnly: true,
        sameSite: 'lax',
        secure: process.env.NODE_ENV === 'production',
        path: '/',
        maxAge: 60 * 60 * 24 * 7,
      });
      return res;
    })
  )
);
