import { pgTable, serial, text, integer, doublePrecision, timestamp, jsonb } from "drizzle-orm/pg-core";

export const contratos = pgTable("contratos", {
  id: serial("id").primaryKey(),
  direccion: text("direccion").notNull(),
  locadora: text("locadora").notNull(),
  locatarios: text("locatarios").notNull(),
  fechaInicio: text("fecha_inicio").notNull(),
  fechaFin: text("fecha_fin").notNull(),
  montoBaseInicial: integer("monto_base_inicial").notNull(),
  diaVencimiento: integer("dia_vencimiento").notNull().default(5),
  penalDiario: doublePrecision("penal_diario").notNull().default(0.003),
  calendarioAjustes: jsonb("calendario_ajustes"),
});

export const indicesIpc = pgTable("indices_ipc", {
  id: serial("id").primaryKey(),
  anio: integer("anio").notNull(),
  mes: integer("mes").notNull(),
  valor: doublePrecision("valor").notNull(),
  variacionMensual: doublePrecision("variacion_mensual"),
  fuente: text("fuente").default("INDEC"),
  creadoEn: timestamp("creado_en").defaultNow(),
});

export const ajustesIpc = pgTable("ajustes_ipc", {
  id: serial("id").primaryKey(),
  contratoId: integer("contrato_id").notNull(),
  fechaAjuste: text("fecha_ajuste").notNull(),
  mesIndiceInicio: text("mes_indice_inicio").notNull(),
  mesIndiceFin: text("mes_indice_fin").notNull(),
  indiceInicio: doublePrecision("indice_inicio").notNull(),
  indiceFin: doublePrecision("indice_fin").notNull(),
  coeficiente: doublePrecision("coeficiente").notNull(),
  montoAnterior: integer("monto_anterior").notNull(),
  montoNuevo: integer("monto_nuevo").notNull(),
});

export const cuotasEsperadas = pgTable("cuotas_esperadas", {
  id: serial("id").primaryKey(),
  contratoId: integer("contrato_id").notNull(),
  periodo: text("periodo").notNull(),
  montoEsperadoIpc: integer("monto_esperado_ipc").notNull(),
  montoAcordado: integer("monto_acordado"),
  fechaVencimiento: text("fecha_vencimiento").notNull(),
});

export const pagos = pgTable("pagos", {
  id: serial("id").primaryKey(),
  contratoId: integer("contrato_id").notNull(),
  periodo: text("periodo").notNull(),
  fechaPago: text("fecha_pago"),
  monto: integer("monto").notNull(),
  notas: text("notas"),
  creadoEn: timestamp("creado_en").defaultNow(),
  creadoPor: text("creado_por"),
  estado: text("estado"),
});

export const servicios = pgTable("servicios", {
  id: serial("id").primaryKey(),
  nombre: text("nombre").notNull(),
  porcentaje: integer("porcentaje").notNull().default(45),
  color: text("color").default("#64748b"),
  activo: integer("activo").default(1),
  createdAt: timestamp("created_at").defaultNow(),
});

export const gastosServicios = pgTable("gastos_servicios", {
  id: serial("id").primaryKey(),
  servicioId: integer("servicio_id").notNull(),
  periodo: text("periodo").notNull(),
  montoFacturado: doublePrecision("monto_facturado").notNull(),
  montoPagado: doublePrecision("monto_pagado").default(0),
  fechaPago: text("fecha_pago"),
  fechaCompletado: text("fecha_completado"),
  notas: text("notas"),
  createdAt: timestamp("created_at").defaultNow(),
  updatedAt: timestamp("updated_at").defaultNow(),
});

export const pagosServicios = pgTable("pagos_servicios", {
  id: serial("id").primaryKey(),
  fecha: text("fecha").notNull(),
  monto: doublePrecision("monto").notNull(),
  notas: text("notas"),
  creadoPor: text("creado_por"),
  porcentajeCubierto: doublePrecision("porcentaje_cubierto"),
  createdAt: timestamp("created_at").defaultNow(),
});

export const usuariosApp = pgTable("usuarios_app", {
  id: serial("id").primaryKey(),
  authUid: text("auth_uid").unique(),
  email: text("email").notNull().unique(),
  nombre: text("nombre").notNull(),
  rol: text("rol").notNull().default("inquilino"),
  permisos: jsonb("permisos"),
  activo: integer("activo").notNull().default(1),
  createdAt: timestamp("created_at").defaultNow(),
});

export const archivos = pgTable("archivos", {
  id: serial("id").primaryKey(),
  tipo: text("tipo").notNull(), // 'recibo' | 'factura'
  seccion: text("seccion").notNull(), // 'pagos' | 'servicios'
  referenciaId: integer("referencia_id").notNull(),
  periodo: text("periodo"),
  nombreArchivo: text("nombre_archivo").notNull(),
  storagePath: text("storage_path").notNull(),
  contentType: text("content_type"),
  sizeBytes: integer("size_bytes"),
  subidoPor: text("subido_por"),
  createdAt: timestamp("created_at").defaultNow(),
});

export const historialCambios = pgTable("historial_cambios", {
  id: serial("id").primaryKey(),
  tabla: text("tabla").notNull(),
  registroId: integer("registro_id").notNull(),
  campo: text("campo").notNull(),
  valorAnterior: text("valor_anterior"),
  valorNuevo: text("valor_nuevo"),
  usuario: text("usuario").notNull(),
  createdAt: timestamp("created_at").defaultNow(),
});

export const botSessions = pgTable("bot_sessions", {
  id: serial("id").primaryKey(),
  phone: text("phone").notNull().unique(),
  state: text("state").notNull().default("idle"),
  context: jsonb("context").default({}),
  updatedAt: timestamp("updated_at").defaultNow(),
});

export const configuracion = pgTable("configuracion", {
  clave: text("clave").primaryKey(),
  valor: text("valor").notNull(),
  updatedAt: timestamp("updated_at").defaultNow(),
});
