import { Role } from '@prisma/client';
import prisma from '../config/db';

export const resolveOperationalUser = async (preferredRole: Role = Role.ADMIN) => {
  const preferredUser = await prisma.user.findFirst({
    where: {
      active: true,
      role: preferredRole,
    },
    orderBy: {
      createdAt: 'asc',
    },
  });

  if (preferredUser) {
    return preferredUser;
  }

  if (preferredRole !== Role.ADMIN) {
    const adminUser = await prisma.user.findFirst({
      where: {
        active: true,
        role: Role.ADMIN,
      },
      orderBy: {
        createdAt: 'asc',
      },
    });

    if (adminUser) {
      return adminUser;
    }
  }

  throw new Error(
    `No existe un usuario activo disponible para operar con el rol ${preferredRole}. Crea primero el usuario real en Configuracion.`,
  );
};

export const resolveGenericTreatment = async (name: string, costBase: number) => {
  const normalizedName = name.trim() || 'Tratamiento general';

  const existingTreatment = await prisma.tratamiento.findFirst({
    where: { nombre: normalizedName },
    orderBy: { id: 'asc' },
  });

  if (existingTreatment) {
    return existingTreatment;
  }

  return prisma.tratamiento.create({
    data: {
      nombre: normalizedName,
      descripcion: normalizedName,
      costoBase: costBase,
      activo: true,
    },
  });
};

export const resolveCashPatient = async () => {
  const existingPatient = await prisma.paciente.findFirst({
    where: {
      tipoDocumento: 'DNI',
      dni: '00000000',
    },
  });

  if (existingPatient) {
    return existingPatient;
  }

  return prisma.paciente.create({
    data: {
      tipoDocumento: 'DNI',
      dni: '00000000',
      nombres: 'Caja',
      apellidos: 'General',
      email: 'caja@dentaflow.local',
      telefono: null,
    },
  });
};

export const buildReferenceCode = (prefix: string) => {
  const date = new Date();
  const datePart = [
    date.getFullYear(),
    String(date.getMonth() + 1).padStart(2, '0'),
    String(date.getDate()).padStart(2, '0'),
  ].join('');
  const timePart = [
    String(date.getHours()).padStart(2, '0'),
    String(date.getMinutes()).padStart(2, '0'),
    String(date.getSeconds()).padStart(2, '0'),
  ].join('');
  const randomPart = Math.floor(Math.random() * 900 + 100);

  return `${prefix}-${datePart}-${timePart}-${randomPart}`;
};
