import { PMO_TABLES } from '../pmo/schema.js';
export class TrelloMapper {
    db;
    constructor(db) {
        this.db = db;
        this.ensureTable();
    }
    ensureTable() {
        this.db.exec(`
      CREATE TABLE IF NOT EXISTS ${PMO_TABLES.trello_card_map} (
        pmo_ticket_id TEXT NOT NULL REFERENCES ${PMO_TABLES.tickets}(id) ON DELETE CASCADE,
        trello_card_id TEXT NOT NULL,
        trello_board_id TEXT,
        last_synced_at TIMESTAMP,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (pmo_ticket_id),
        UNIQUE (trello_card_id)
      )
    `);
        this.db.exec(`
      CREATE INDEX IF NOT EXISTS idx_pmo_trello_card_map_card_id
        ON ${PMO_TABLES.trello_card_map}(trello_card_id)
    `);
    }
    createOrUpdateMapping(pmoTicketId, trelloCardId, trelloBoardId) {
        this.db.prepare(`
      INSERT INTO ${PMO_TABLES.trello_card_map}
        (pmo_ticket_id, trello_card_id, trello_board_id, last_synced_at, created_at)
      VALUES (?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
      ON CONFLICT(pmo_ticket_id) DO UPDATE SET
        trello_card_id = excluded.trello_card_id,
        trello_board_id = excluded.trello_board_id,
        last_synced_at = CURRENT_TIMESTAMP
    `).run(pmoTicketId, trelloCardId, trelloBoardId ?? null);
    }
    getByTicketId(ticketId) {
        const row = this.db.prepare(`
      SELECT * FROM ${PMO_TABLES.trello_card_map} WHERE pmo_ticket_id = ?
    `).get(ticketId);
        return row ? this.rowToMap(row) : null;
    }
    getByCardId(trelloCardId) {
        const row = this.db.prepare(`
      SELECT * FROM ${PMO_TABLES.trello_card_map} WHERE trello_card_id = ?
    `).get(trelloCardId);
        return row ? this.rowToMap(row) : null;
    }
    listMappings() {
        const rows = this.db.prepare(`
      SELECT * FROM ${PMO_TABLES.trello_card_map} ORDER BY created_at DESC
    `).all();
        return rows.map((row) => this.rowToMap(row));
    }
    updateSyncTimestamp(ticketId) {
        this.db.prepare(`
      UPDATE ${PMO_TABLES.trello_card_map}
      SET last_synced_at = CURRENT_TIMESTAMP
      WHERE pmo_ticket_id = ?
    `).run(ticketId);
    }
    rowToMap(row) {
        return {
            pmoTicketId: row.pmo_ticket_id,
            trelloCardId: row.trello_card_id,
            trelloBoardId: row.trello_board_id ?? undefined,
            lastSyncedAt: row.last_synced_at ? new Date(row.last_synced_at) : undefined,
            createdAt: new Date(row.created_at),
        };
    }
}
//# sourceMappingURL=mapper.js.map