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

class OffboardingProtocol {
    /**
     * Get all offboarding protocols with related information
     */
    static getAll() {
        const db = getDatabase();
        const stmt = db.prepare(`
            SELECT
                op.*,
                e.username as employee_username,
                e.first_name as employee_first_name,
                e.last_name as employee_last_name,
                e.email as employee_email,
                r.name as employee_role_name,
                cu.username as created_by_username,
                uu.username as updated_by_username
            FROM offboarding_protocols op
            INNER JOIN users e ON op.employee_user_id = e.id
            INNER JOIN roles r ON e.role_id = r.id
            LEFT JOIN users cu ON op.created_by_user_id = cu.id
            LEFT JOIN users uu ON op.updated_by_user_id = uu.id
            ORDER BY op.created_at DESC
        `);
        return stmt.all();
    }

    /**
     * Get offboarding protocol by ID
     */
    static getById(id) {
        const db = getDatabase();
        const stmt = db.prepare(`
            SELECT
                op.*,
                e.username as employee_username,
                e.first_name as employee_first_name,
                e.last_name as employee_last_name,
                e.email as employee_email,
                e.department as employee_department,
                r.name as employee_role_name,
                cu.username as created_by_username,
                uu.username as updated_by_username,
                (SELECT d.id FROM onboarding_departments d
                 WHERE LOWER(d.name) LIKE LOWER('%' || COALESCE(e.department,'') || '%')
                   AND COALESCE(e.department,'') != ''
                 ORDER BY d.id LIMIT 1) as employee_department_id
            FROM offboarding_protocols op
            INNER JOIN users e ON op.employee_user_id = e.id
            INNER JOIN roles r ON e.role_id = r.id
            LEFT JOIN users cu ON op.created_by_user_id = cu.id
            LEFT JOIN users uu ON op.updated_by_user_id = uu.id
            WHERE op.id = ?
        `);
        return stmt.get(id);
    }

    /**
     * Get offboarding protocols by status
     */
    static getByStatus(status) {
        const db = getDatabase();
        const stmt = db.prepare(`
            SELECT
                op.*,
                e.username as employee_username,
                e.first_name as employee_first_name,
                e.last_name as employee_last_name,
                e.email as employee_email,
                cu.username as created_by_username
            FROM offboarding_protocols op
            INNER JOIN users e ON op.employee_user_id = e.id
            LEFT JOIN users cu ON op.created_by_user_id = cu.id
            WHERE op.status = ?
            ORDER BY op.created_at DESC
        `);
        return stmt.all(status);
    }

    /**
     * Get offboarding protocols for an employee
     */
    static getByEmployee(employeeUserId) {
        const db = getDatabase();
        const stmt = db.prepare(`
            SELECT
                op.*,
                cu.username as created_by_username
            FROM offboarding_protocols op
            LEFT JOIN users cu ON op.created_by_user_id = cu.id
            WHERE op.employee_user_id = ?
            ORDER BY op.created_at DESC
        `);
        return stmt.all(employeeUserId);
    }

    /**
     * Create a new offboarding protocol
     */
    static create(protocolData) {
        const db = getDatabase();
        const stmt = db.prepare(`
            INSERT INTO offboarding_protocols (
                employee_user_id,
                status,
                exit_date,
                checklist_data,
                notes,
                created_by_user_id
            ) VALUES (?, ?, ?, ?, ?, ?)
        `);

        const result = stmt.run(
            protocolData.employee_user_id,
            protocolData.status,
            protocolData.exit_date,
            protocolData.checklist_data || null,
            protocolData.notes || null,
            protocolData.created_by_user_id
        );

        return this.getById(result.lastInsertRowid);
    }

    /**
     * Update offboarding protocol
     */
    static update(id, protocolData, updatedByUserId) {
        const db = getDatabase();

        const fields = [];
        const values = [];

        if (protocolData.status !== undefined) {
            fields.push('status = ?');
            values.push(protocolData.status);
        }
        if (protocolData.exit_date !== undefined) {
            fields.push('exit_date = ?');
            values.push(protocolData.exit_date);
        }
        if (protocolData.completion_date !== undefined) {
            fields.push('completion_date = ?');
            values.push(protocolData.completion_date);
        }
        if (protocolData.checklist_data !== undefined) {
            fields.push('checklist_data = ?');
            values.push(protocolData.checklist_data);
        }
        if (protocolData.notes !== undefined) {
            fields.push('notes = ?');
            values.push(protocolData.notes);
        }
        if (protocolData.pdf_file_path !== undefined) {
            fields.push('pdf_file_path = ?');
            values.push(protocolData.pdf_file_path);
        }

        fields.push('updated_by_user_id = ?');
        fields.push('updated_at = CURRENT_TIMESTAMP');
        values.push(updatedByUserId, id);

        const stmt = db.prepare(`
            UPDATE offboarding_protocols
            SET ${fields.join(', ')}
            WHERE id = ?
        `);

        stmt.run(...values);
        return this.getById(id);
    }

    /**
     * Update checklist data
     */
    static updateChecklist(id, checklistData, updatedByUserId) {
        const db = getDatabase();
        const stmt = db.prepare(`
            UPDATE offboarding_protocols
            SET checklist_data = ?,
                updated_by_user_id = ?,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        `);

        stmt.run(checklistData, updatedByUserId, id);
        return this.getById(id);
    }

    /**
     * Update PDF file path
     */
    static updatePdfPath(id, pdfFilePath, updatedByUserId) {
        const db = getDatabase();
        const stmt = db.prepare(`
            UPDATE offboarding_protocols
            SET pdf_file_path = ?,
                updated_by_user_id = ?,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        `);

        stmt.run(pdfFilePath, updatedByUserId, id);
        return this.getById(id);
    }

    /**
     * Delete offboarding protocol
     */
    static delete(id) {
        const db = getDatabase();
        const stmt = db.prepare('DELETE FROM offboarding_protocols WHERE id = ?');
        const result = stmt.run(id);
        return result.changes > 0;
    }

    /**
     * Get statistics
     */
    static getStatistics() {
        const db = getDatabase();

        const totalStmt = db.prepare('SELECT COUNT(*) as total FROM offboarding_protocols');
        const pendingStmt = db.prepare("SELECT COUNT(*) as pending FROM offboarding_protocols WHERE status = 'pending'");
        const inProgressStmt = db.prepare("SELECT COUNT(*) as in_progress FROM offboarding_protocols WHERE status = 'in_progress'");
        const completedStmt = db.prepare("SELECT COUNT(*) as completed FROM offboarding_protocols WHERE status = 'completed'");

        return {
            total: totalStmt.get().total,
            pending: pendingStmt.get().pending,
            in_progress: inProgressStmt.get().in_progress,
            completed: completedStmt.get().completed
        };
    }
}

module.exports = OffboardingProtocol;
