/**
 * SQLite AgentQuestion Repository (spec 093)
 *
 * Backed by the agent_questions table (migration 088). Every read is
 * scoped by app_id at the SQL layer (NFR-7).
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { injectable } from 'tsyringe';
import { AgentQuestionStatus as AgentQuestionStatusEnum } from '../../domain/generated/output.js';
import { toDatabase, fromDatabase, } from '../persistence/sqlite/mappers/agent-question.mapper.js';
let SQLiteAgentQuestionRepository = class SQLiteAgentQuestionRepository {
    db;
    constructor(db) {
        this.db = db;
    }
    async create(question) {
        const row = toDatabase(question);
        const stmt = this.db.prepare(`
      INSERT INTO agent_questions (
        id, app_id, feature_id, agent_run_id, kind, prompt,
        options_json, default_answer, answerer, status,
        answer, answered_by, answered_at, expires_at,
        created_at, updated_at
      ) VALUES (
        @id, @app_id, @feature_id, @agent_run_id, @kind, @prompt,
        @options_json, @default_answer, @answerer, @status,
        @answer, @answered_by, @answered_at, @expires_at,
        @created_at, @updated_at
      )
    `);
        stmt.run(row);
    }
    async findById(appId, id) {
        const stmt = this.db.prepare('SELECT * FROM agent_questions WHERE id = ? AND app_id = ?');
        const row = stmt.get(id, appId);
        return row ? fromDatabase(row) : null;
    }
    async listByScope(appId, featureId, filters = {}) {
        const conditions = ['app_id = ?'];
        const params = [appId];
        if (featureId !== undefined) {
            conditions.push('feature_id = ?');
            params.push(featureId);
        }
        if (filters.status !== undefined) {
            conditions.push('status = ?');
            params.push(filters.status);
        }
        const limitClause = filters.limit !== undefined ? ' LIMIT ?' : '';
        if (filters.limit !== undefined) {
            params.push(filters.limit);
        }
        const sql = `SELECT * FROM agent_questions WHERE ${conditions.join(' AND ')} ORDER BY created_at DESC${limitClause}`;
        const rows = this.db.prepare(sql).all(...params);
        return rows.map(fromDatabase);
    }
    async listByAgentRun(appId, agentRunId) {
        const stmt = this.db.prepare('SELECT * FROM agent_questions WHERE app_id = ? AND agent_run_id = ? ORDER BY created_at DESC');
        const rows = stmt.all(appId, agentRunId);
        return rows.map(fromDatabase);
    }
    async updateStatus(appId, id, status, fields = {}) {
        const now = Date.now();
        const setClauses = ['status = ?', 'updated_at = ?'];
        const values = [status, now];
        if (fields.answer !== undefined) {
            setClauses.push('answer = ?');
            values.push(fields.answer);
        }
        if (fields.answeredBy !== undefined) {
            setClauses.push('answered_by = ?');
            values.push(fields.answeredBy);
        }
        if (fields.answeredAt !== undefined) {
            setClauses.push('answered_at = ?');
            values.push(fields.answeredAt instanceof Date ? fields.answeredAt.getTime() : Number(fields.answeredAt));
        }
        values.push(id, appId);
        const stmt = this.db.prepare(`UPDATE agent_questions SET ${setClauses.join(', ')} WHERE id = ? AND app_id = ?`);
        stmt.run(...values);
    }
    async findExpired(cutoff, limit) {
        const limitClause = limit !== undefined ? ' LIMIT ?' : '';
        const params = [AgentQuestionStatusEnum.pending, cutoff.getTime()];
        if (limit !== undefined)
            params.push(limit);
        const sql = `SELECT * FROM agent_questions WHERE status = ? AND expires_at IS NOT NULL AND expires_at <= ? ORDER BY expires_at ASC${limitClause}`;
        const rows = this.db.prepare(sql).all(...params);
        return rows.map(fromDatabase);
    }
};
SQLiteAgentQuestionRepository = __decorate([
    injectable(),
    __metadata("design:paramtypes", [Object])
], SQLiteAgentQuestionRepository);
export { SQLiteAgentQuestionRepository };
