import type { DatabaseSync } from "node:sqlite";
import type { ComplaintResult, ComplaintRow } from "./types.js";

export function initSchema(db: DatabaseSync): void {
  db.exec(`
    CREATE TABLE IF NOT EXISTS complaints (
      id          INTEGER PRIMARY KEY AUTOINCREMENT,
      agent_id    TEXT,
      channel_id  TEXT    NOT NULL,
      chat_id     TEXT    NOT NULL,
      from_sender TEXT    NOT NULL,
      content     TEXT    NOT NULL,
      is_complaint INTEGER NOT NULL DEFAULT 0,
      severity    TEXT    NOT NULL DEFAULT 'low',
      category    TEXT    NOT NULL DEFAULT 'other',
      summary     TEXT    NOT NULL DEFAULT '',
      created_at  INTEGER NOT NULL,
      notified_at INTEGER
    );
    CREATE INDEX IF NOT EXISTS idx_complaints_chat_id ON complaints(chat_id, created_at);
  `);
}

export interface InsertComplaintParams {
  agentId?: string | null;
  channelId: string;
  chatId: string;
  fromSender: string;
  content: string;
  result: ComplaintResult;
}

export function insertComplaint(db: DatabaseSync, p: InsertComplaintParams): number {
  const run = db
    .prepare(
      `INSERT INTO complaints
        (agent_id, channel_id, chat_id, from_sender, content, is_complaint, severity, category, summary, created_at)
       VALUES (?,?,?,?,?,?,?,?,?,?)`,
    )
    .run(
      p.agentId ?? null,
      p.channelId,
      p.chatId,
      p.fromSender,
      p.content,
      p.result.is_complaint ? 1 : 0,
      p.result.severity,
      p.result.category,
      p.result.summary,
      Date.now(),
    );
  return Number(run.lastInsertRowid);
}

export function markNotified(db: DatabaseSync, id: number): void {
  db.prepare("UPDATE complaints SET notified_at = ? WHERE id = ?").run(Date.now(), id);
}

export function getPendingNotifications(db: DatabaseSync): ComplaintRow[] {
  return db
    .prepare(
      "SELECT * FROM complaints WHERE is_complaint = 1 AND notified_at IS NULL ORDER BY created_at ASC",
    )
    .all() as ComplaintRow[];
}

export function getComplaintById(db: DatabaseSync, id: number): ComplaintRow | undefined {
  return db.prepare("SELECT * FROM complaints WHERE id = ?").get(id) as ComplaintRow | undefined;
}

export function countBySeverity(db: DatabaseSync, severity: string): number {
  const row = db
    .prepare("SELECT COUNT(*) as cnt FROM complaints WHERE severity = ? AND is_complaint = 1")
    .get(severity) as { cnt: number } | undefined;
  return row?.cnt ?? 0;
}

export function getComplaintsByChatId(
  db: DatabaseSync,
  chatId: string,
  limit: number,
): ComplaintRow[] {
  return db
    .prepare(
      "SELECT * FROM complaints WHERE chat_id = ? ORDER BY created_at DESC LIMIT ?",
    )
    .all(chatId, limit) as ComplaintRow[];
}

export function getRecentComplaints(db: DatabaseSync, limit: number): ComplaintRow[] {
  return db
    .prepare(
      "SELECT * FROM complaints WHERE is_complaint = 1 ORDER BY created_at DESC, id DESC LIMIT ?",
    )
    .all(limit) as ComplaintRow[];
}
