const { getDatabase } = require('../config/database');

const ExternalAlert = {
    getAll({ limit = 100, acknowledged } = {}) {
        const db = getDatabase();
        let q = `SELECT * FROM external_alerts`;
        const params = [];
        if (acknowledged !== undefined) {
            q += ` WHERE acknowledged = ?`;
            params.push(acknowledged ? 1 : 0);
        }
        q += ` ORDER BY created_at DESC LIMIT ?`;
        params.push(limit);
        return db.prepare(q).all(...params);
    },

    getById(id) {
        const db = getDatabase();
        return db.prepare(`SELECT * FROM external_alerts WHERE id = ?`).get(id);
    },

    getByEmailMessageId(messageId) {
        const db = getDatabase();
        return db.prepare(`SELECT id FROM external_alerts WHERE email_message_id = ?`).get(messageId);
    },

    create(data) {
        const db = getDatabase();
        const stmt = db.prepare(`
            INSERT INTO external_alerts
                (source, device, service, state_transition, severity, message, customer, monitored_by, state_time, raw_body, email_message_id)
            VALUES
                (@source, @device, @service, @state_transition, @severity, @message, @customer, @monitored_by, @state_time, @raw_body, @email_message_id)
        `);
        const result = stmt.run({
            source: data.source || 'netgo',
            device: data.device || '',
            service: data.service || '',
            state_transition: data.state_transition || '',
            severity: data.severity || 'UNKNOWN',
            message: data.message || '',
            customer: data.customer || '',
            monitored_by: data.monitored_by || '',
            state_time: data.state_time || '',
            raw_body: data.raw_body || '',
            email_message_id: data.email_message_id || null,
        });
        return this.getById(result.lastInsertRowid);
    },

    setAiAnalysis(id, analysis) {
        const db = getDatabase();
        db.prepare(`UPDATE external_alerts SET ai_analysis = ? WHERE id = ?`).run(
            typeof analysis === 'string' ? analysis : JSON.stringify(analysis),
            id
        );
    },

    acknowledge(id) {
        const db = getDatabase();
        db.prepare(`UPDATE external_alerts SET acknowledged = 1 WHERE id = ?`).run(id);
        return this.getById(id);
    },

    setTicket(id, ticketId) {
        const db = getDatabase();
        db.prepare(`UPDATE external_alerts SET ticket_id = ?, acknowledged = 1 WHERE id = ?`).run(ticketId, id);
        return this.getById(id);
    },

    delete(id) {
        const db = getDatabase();
        db.prepare(`DELETE FROM external_alerts WHERE id = ?`).run(id);
    },

    getUnacknowledgedCount() {
        const db = getDatabase();
        return db.prepare(`SELECT COUNT(*) as count FROM external_alerts WHERE acknowledged = 0`).get().count;
    },
};

module.exports = ExternalAlert;
