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

class TicketComment {
    /**
     * Get all comments for a ticket
     */
    static getByTicketId(ticketId) {
        const db = getDatabase();
        return db.prepare(`
            SELECT
                tc.*,
                u.username,
                u.first_name,
                u.last_name,
                u.role_id
            FROM ticket_comments tc
            LEFT JOIN users u ON tc.user_id = u.id
            WHERE tc.ticket_id = ?
            ORDER BY tc.created_at ASC
        `).all(ticketId);
    }

    /**
     * Create a new comment
     */
    static create(ticketId, userId, comment, isInternal = false, isAiComment = false) {
        const db = getDatabase();
        const result = db.prepare(`
            INSERT INTO ticket_comments (ticket_id, user_id, comment, is_internal, is_ai_comment)
            VALUES (?, ?, ?, ?, ?)
        `).run(ticketId, userId || null, comment, isInternal ? 1 : 0, isAiComment ? 1 : 0);

        return db.prepare(`
            SELECT tc.*, u.username, u.first_name, u.last_name, u.role_id
            FROM ticket_comments tc
            LEFT JOIN users u ON tc.user_id = u.id
            WHERE tc.id = ?
        `).get(result.lastInsertRowid);
    }

    /**
     * Delete a comment
     */
    static delete(id) {
        const db = getDatabase();
        return db.prepare('DELETE FROM ticket_comments WHERE id = ?').run(id).changes > 0;
    }
}

module.exports = TicketComment;
