import { selectComplex } from '@/modules/complex/services/complex.service';
import type { AppContext } from '@/types/hono';
import { setCookie } from 'hono/cookie';
import { z } from 'zod';

const SELECTED_COMPLEX_COOKIE = 'selected-complex-id';
const COOKIE_MAX_AGE = 60 * 60 * 24 * 30;

const selectComplexSchema = z.object({
  complexId: z.string().uuid(),
});

export async function selectComplexHandler(c: AppContext) {
  const user = c.get('user');
  const body = await c.req.json();
  const result = selectComplexSchema.safeParse(body);

  if (!result.success) {
    return c.json({ message: 'Invalid payload', issues: result.error.issues }, { status: 400 });
  }

  const { complexId } = result.data;
  const complex = await selectComplex(user.id, complexId);

  if (!complex) {
    return c.json({ message: 'Complex not found or not associated with user' }, { status: 404 });
  }

  setCookie(c, SELECTED_COMPLEX_COOKIE, complexId, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict',
    path: '/',
    maxAge: COOKIE_MAX_AGE,
  });

  return c.json(complex);
}
