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