import type { Pool } from 'pg';
import type { AlertaFull, AlertaCreate, AlertaUpdate, AlertasStats } from '@horux/shared';

export async function getAlertas(
  pool: Pool,
  filters: { leida?: boolean; resuelta?: boolean; prioridad?: string }
): Promise<AlertaFull[]> {
  let whereClause = 'WHERE 1=1';
  const params: any[] = [];
  let paramIndex = 1;

  if (filters.leida !== undefined) {
    whereClause += ` AND leida = $${paramIndex++}`;
    params.push(filters.leida);
  }
  if (filters.resuelta !== undefined) {
    whereClause += ` AND resuelta = $${paramIndex++}`;
    params.push(filters.resuelta);
  }
  if (filters.prioridad) {
    whereClause += ` AND prioridad = $${paramIndex++}`;
    params.push(filters.prioridad);
  }

  const { rows } = await pool.query(`
    SELECT id, tipo, titulo, mensaje, prioridad,
           fecha_vencimiento as "fechaVencimiento",
           leida, resuelta, created_at as "createdAt"
    FROM alertas
    ${whereClause}
    ORDER BY
      CASE prioridad WHEN 'alta' THEN 1 WHEN 'media' THEN 2 ELSE 3 END,
      created_at DESC
  `, params);

  return rows;
}

export async function getAlertaById(pool: Pool, id: number): Promise<AlertaFull | null> {
  const { rows } = await pool.query(`
    SELECT id, tipo, titulo, mensaje, prioridad,
           fecha_vencimiento as "fechaVencimiento",
           leida, resuelta, created_at as "createdAt"
    FROM alertas
    WHERE id = $1
  `, [id]);
  return rows[0] || null;
}

export async function createAlerta(pool: Pool, data: AlertaCreate): Promise<AlertaFull> {
  const { rows } = await pool.query(`
    INSERT INTO alertas (tipo, titulo, mensaje, prioridad, fecha_vencimiento)
    VALUES ($1, $2, $3, $4, $5)
    RETURNING id, tipo, titulo, mensaje, prioridad,
              fecha_vencimiento as "fechaVencimiento",
              leida, resuelta, created_at as "createdAt"
  `, [data.tipo, data.titulo, data.mensaje, data.prioridad, data.fechaVencimiento || null]);
  return rows[0];
}

export async function updateAlerta(pool: Pool, id: number, data: AlertaUpdate): Promise<AlertaFull> {
  const sets: string[] = [];
  const params: any[] = [];
  let paramIndex = 1;

  if (data.leida !== undefined) {
    sets.push(`leida = $${paramIndex++}`);
    params.push(data.leida);
  }
  if (data.resuelta !== undefined) {
    sets.push(`resuelta = $${paramIndex++}`);
    params.push(data.resuelta);
  }

  params.push(id);

  const { rows } = await pool.query(`
    UPDATE alertas
    SET ${sets.join(', ')}
    WHERE id = $${paramIndex}
    RETURNING id, tipo, titulo, mensaje, prioridad,
              fecha_vencimiento as "fechaVencimiento",
              leida, resuelta, created_at as "createdAt"
  `, params);

  return rows[0];
}

export async function deleteAlerta(pool: Pool, id: number): Promise<void> {
  await pool.query(`DELETE FROM alertas WHERE id = $1`, [id]);
}

export async function getStats(pool: Pool): Promise<AlertasStats> {
  const { rows: [stats] } = await pool.query(`
    SELECT
      COUNT(*)::int as total,
      COUNT(CASE WHEN leida = false THEN 1 END)::int as "noLeidas",
      COUNT(CASE WHEN prioridad = 'alta' AND resuelta = false THEN 1 END)::int as alta,
      COUNT(CASE WHEN prioridad = 'media' AND resuelta = false THEN 1 END)::int as media,
      COUNT(CASE WHEN prioridad = 'baja' AND resuelta = false THEN 1 END)::int as baja
    FROM alertas
  `);
  return stats;
}

export async function markAllAsRead(pool: Pool): Promise<void> {
  await pool.query(`UPDATE alertas SET leida = true WHERE leida = false`);
}
