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

class User {
    static getAll() {
        const db = getDatabase();
        const stmt = db.prepare(`
            SELECT
                u.id, u.username, u.email, u.first_name, u.last_name,
                u.is_active, u.must_change_password, u.email_notifications, u.last_login,
                u.created_at, u.updated_at, u.role_id, u.azure_id,
                u.department, u.position, u.phone, u.location, u.manager_id,
                u.cost_center, u.employment_type, u.work_hours, u.joined_date, u.avatar_url,
                r.name as role_name, r.description as role_description
            FROM users u
            LEFT JOIN roles r ON u.role_id = r.id
            ORDER BY u.created_at DESC
        `);
        return stmt.all();
    }

    static getById(id) {
        const db = getDatabase();
        const stmt = db.prepare(`
            SELECT
                u.id, u.username, u.email, u.first_name, u.last_name,
                u.is_active, u.must_change_password, u.email_notifications, u.last_login,
                u.created_at, u.updated_at, u.role_id, u.azure_id,
                u.department, u.position, u.phone, u.location, u.manager_id,
                u.cost_center, u.employment_type, u.work_hours, u.joined_date, u.avatar_url,
                r.name as role_name, r.description as role_description
            FROM users u
            LEFT JOIN roles r ON u.role_id = r.id
            WHERE u.id = ?
        `);
        return stmt.get(id);
    }

    static getByIdWithPassword(id) {
        const db = getDatabase();
        const stmt = db.prepare(`
            SELECT u.*, r.name as role_name, r.description as role_description
            FROM users u
            LEFT JOIN roles r ON u.role_id = r.id
            WHERE u.id = ?
        `);
        return stmt.get(id);
    }

    static getByUsername(username) {
        const db = getDatabase();
        const stmt = db.prepare(`
            SELECT u.*, r.name as role_name
            FROM users u
            LEFT JOIN roles r ON u.role_id = r.id
            WHERE u.username = ?
        `);
        return stmt.get(username);
    }

    static getByEmail(email) {
        const db = getDatabase();
        const stmt = db.prepare(`
            SELECT u.*, r.name as role_name
            FROM users u
            LEFT JOIN roles r ON u.role_id = r.id
            WHERE u.email = ?
        `);
        return stmt.get(email);
    }

    static getByAzureId(azureId) {
        const db = getDatabase();
        const stmt = db.prepare(`
            SELECT u.*, r.name as role_name
            FROM users u
            LEFT JOIN roles r ON u.role_id = r.id
            WHERE u.azure_id = ?
        `);
        return stmt.get(azureId);
    }

    static createFromAzure({ azure_id, email, first_name, last_name, username }) {
        const db = getDatabase();
        const role = db.prepare("SELECT id FROM roles WHERE name = 'benutzer'").get();
        const stmt = db.prepare(`
            INSERT INTO users (username, email, password_hash, role_id, first_name, last_name, is_active, must_change_password, azure_id)
            VALUES (?, ?, 'AZURE_SSO_NO_PASSWORD', ?, ?, ?, 1, 0, ?)
        `);
        const result = stmt.run(username, email, role.id, first_name || null, last_name || null, azure_id);
        return this.getById(result.lastInsertRowid);
    }

    static create(userData) {
        const db = getDatabase();
        const stmt = db.prepare(`
            INSERT INTO users (
                username, email, password_hash, role_id,
                first_name, last_name, is_active, must_change_password
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        `);
        const result = stmt.run(
            userData.username,
            userData.email,
            userData.password_hash,
            userData.role_id,
            userData.first_name || null,
            userData.last_name || null,
            userData.is_active !== undefined ? (userData.is_active ? 1 : 0) : 1,
            userData.must_change_password !== undefined ? (userData.must_change_password ? 1 : 0) : 1
        );
        return this.getById(result.lastInsertRowid);
    }

    static update(id, userData) {
        const db = getDatabase();
        const fields = [];
        const values = [];

        if (userData.username !== undefined) { fields.push('username = ?'); values.push(userData.username); }
        if (userData.email !== undefined) { fields.push('email = ?'); values.push(userData.email); }
        if (userData.password_hash !== undefined) { fields.push('password_hash = ?'); values.push(userData.password_hash); }
        if (userData.role_id !== undefined) { fields.push('role_id = ?'); values.push(userData.role_id); }
        if (userData.first_name !== undefined) { fields.push('first_name = ?'); values.push(userData.first_name); }
        if (userData.last_name !== undefined) { fields.push('last_name = ?'); values.push(userData.last_name); }
        if (userData.is_active !== undefined) { fields.push('is_active = ?'); values.push(userData.is_active ? 1 : 0); }
        if (userData.must_change_password !== undefined) { fields.push('must_change_password = ?'); values.push(userData.must_change_password ? 1 : 0); }
        if (userData.azure_id !== undefined) { fields.push('azure_id = ?'); values.push(userData.azure_id); }

        fields.push('updated_at = CURRENT_TIMESTAMP');
        values.push(id);

        const stmt = db.prepare(`UPDATE users SET ${fields.join(', ')} WHERE id = ?`);
        stmt.run(...values);
        return this.getById(id);
    }

    static delete(id) {
        const db = getDatabase();
        const result = db.prepare('DELETE FROM users WHERE id = ?').run(id);
        return result.changes > 0;
    }

    static updateLastLogin(id) {
        const db = getDatabase();
        db.prepare('UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?').run(id);
    }

    static changePassword(id, passwordHash, mustChange = false) {
        const db = getDatabase();
        db.prepare(`
            UPDATE users SET password_hash = ?, must_change_password = ?, updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        `).run(passwordHash, mustChange ? 1 : 0, id);
    }

    static updateEmailNotifications(id, enabled) {
        const db = getDatabase();
        db.prepare('UPDATE users SET email_notifications = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?')
          .run(enabled ? 1 : 0, id);
        return this.getById(id);
    }

    static updateStaffNotifications(id, prefs) {
        const db = getDatabase();
        db.prepare(`UPDATE users SET
            notif_ticket_created = ?,
            notif_ticket_assigned = ?,
            notif_new_comment = ?,
            notif_weekly_report = ?,
            updated_at = CURRENT_TIMESTAMP
            WHERE id = ?`
        ).run(
            prefs.notif_ticket_created ? 1 : 0,
            prefs.notif_ticket_assigned ? 1 : 0,
            prefs.notif_new_comment ? 1 : 0,
            prefs.notif_weekly_report ? 1 : 0,
            id
        );
        return this.getById(id);
    }
}

module.exports = User;
