import { db } from '@/lib/prisma';
import { createComplex } from '@/modules/complex/services/complex.service';
import type { AppContext } from '@/types/hono';
import type { CreateComplexInput } from '@repo/api-contract';

export async function createComplexHandler(c: AppContext) {
  const payload = c.req.valid('json' as never) as CreateComplexInput;

  const user = c.get('user');
  let adminEmail = user?.email;
  let userId = user?.id;

  if (!adminEmail) {
    const body = await c.req.json().catch(() => ({}));
    adminEmail = body.adminEmail;
    userId = body.userId;
  }

  if (!adminEmail) {
    return c.json({ message: 'Se requiere email del administrador.' }, 400);
  }

  if (!userId && adminEmail) {
    const existingUser = await db.user.findUnique({
      where: { email: adminEmail },
      select: { id: true },
    });
    if (!existingUser) {
      return c.json({ message: 'El usuario no existe.' }, 404);
    }
    userId = existingUser.id;
  }

  const complex = await createComplex({
    complexName: payload.complexName,
    physicalAddress: payload.physicalAddress,
    adminEmail,
    userId,
    planCode: payload.planCode,
    city: payload.city,
    state: payload.state,
    country: payload.country,
    setupCourts: payload.setupCourts,
    courtSportId: payload.courtSportId,
    courtStartTime: payload.courtStartTime,
    courtEndTime: payload.courtEndTime,
    courtDaysOfWeek: payload.courtDaysOfWeek,
  });

  return c.json(complex, 201);
}
