import { db } from './db.js';
import { CARDS } from './data/kanbanCards.js';

/**
 * Upsert canonical cards and their references into the database.
 *
 * - Card *content* (title, description, …) is always refreshed from the seed,
 *   so editing card text in `kanbanCards.ts` flows through on next startup.
 * - Card *status* (column) is intentionally NOT overwritten on conflict, so a
 *   user's board moves survive reseeds.
 * - Canonical references use `INSERT OR IGNORE`, so they self-heal if missing
 *   but never duplicate. They are flagged `canonical = 1` and are not removable
 *   from the UI.
 */
export function seed(): void {
  const upsertCard = db.prepare(`
    INSERT INTO cards (id, title, description, details, category, files, notes, status, sort_order, updated_at)
    VALUES (@id, @title, @description, @details, @category, @files, @notes, @status, @sort_order, @updated_at)
    ON CONFLICT(id) DO UPDATE SET
      title       = excluded.title,
      description = excluded.description,
      details     = excluded.details,
      category    = excluded.category,
      files       = excluded.files,
      notes       = excluded.notes,
      sort_order  = excluded.sort_order,
      updated_at  = excluded.updated_at
  `);

  const upsertRef = db.prepare(`
    INSERT OR IGNORE INTO card_references (card_id, label, type, href, canonical)
    VALUES (?, ?, ?, ?, 1)
  `);

  const now = new Date().toISOString();

  const tx = db.transaction(() => {
    for (const c of CARDS) {
      upsertCard.run({
        id: c.id,
        title: c.title,
        description: c.description,
        details: c.details,
        category: c.category,
        files: c.files,
        notes: c.notes,
        status: c.status,
        sort_order: c.sortOrder,
        updated_at: now,
      });
      for (const r of c.references) {
        upsertRef.run(c.id, r.label, r.type, r.href);
      }
    }
  });

  tx();
}

/**
 * Reset the board: drop all user data (comments, tags, user references) and
 * restore every card's status to its canonical column. Called by the
 * `POST /api/kanban/reset` endpoint.
 */
export function resetBoard(): void {
  const canonical = new Map(CARDS.map((c) => [c.id, c.status]));
  const tx = db.transaction(() => {
    db.prepare('DELETE FROM comments').run();
    db.prepare('DELETE FROM tags').run();
    db.prepare('DELETE FROM card_references WHERE canonical = 0').run();
    const set = db.prepare('UPDATE cards SET status = ? WHERE id = ?');
    for (const [id, status] of canonical) {
      set.run(status, id);
    }
  });
  tx();
}
