import { Database } from "bun:sqlite"
import { getConfig } from "../config"

const dbPath = getConfig("dbPath")
export const db = new Database(dbPath)

// Create tables if they don't exist
db.run(`
  CREATE TABLE IF NOT EXISTS prs (
    gitea_pr_id INTEGER PRIMARY KEY,
    repo TEXT NOT NULL,
    pr_number INTEGER NOT NULL,
    discord_thread_id TEXT NOT NULL,
    discord_message_id TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  );

  CREATE TABLE IF NOT EXISTS comments (
    gitea_comment_id INTEGER PRIMARY KEY,
    discord_message_id TEXT NOT NULL,
    discord_thread_id TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  );
`)

console.log(`📊 Database initialized at ${dbPath}`)

// PR operations
export function insertPR(
  giteaPrId: number,
  repo: string,
  prNumber: number,
  discordThreadId: string,
  discordMessageId: string
) {
  db.run(
    `INSERT INTO prs (gitea_pr_id, repo, pr_number, discord_thread_id, discord_message_id)
     VALUES (?, ?, ?, ?, ?)`,
    [giteaPrId, repo, prNumber, discordThreadId, discordMessageId]
  )
}

export function getPRByGiteaId(giteaPrId: number) {
  return db
    .query<
      { discord_thread_id: string; discord_message_id: string; repo: string; pr_number: number },
      number
    >(`SELECT discord_thread_id, discord_message_id, repo, pr_number FROM prs WHERE gitea_pr_id = ?`)
    .get(giteaPrId)
}

export function getPRByDiscordThreadId(discordThreadId: string) {
  return db
    .query<{ gitea_pr_id: number; repo: string; pr_number: number; discord_thread_id: string }, string>(
      `SELECT gitea_pr_id, repo, pr_number, discord_thread_id FROM prs WHERE discord_thread_id = ?`
    )
    .get(discordThreadId)
}

// Comment operations
export function insertComment(giteaCommentId: number, discordMessageId: string, discordThreadId: string) {
  db.run(
    `INSERT INTO comments (gitea_comment_id, discord_message_id, discord_thread_id)
     VALUES (?, ?, ?)`,
    [giteaCommentId, discordMessageId, discordThreadId]
  )
}

export function getCommentByGiteaId(giteaCommentId: number) {
  return db
    .query<{ discord_message_id: string; discord_thread_id: string }, number>(
      `SELECT discord_message_id, discord_thread_id FROM comments WHERE gitea_comment_id = ?`
    )
    .get(giteaCommentId)
}
