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

class License {
    static getAll() {
        const db = getDatabase();
        const stmt = db.prepare(`
            SELECT l.*, u.username as created_by_username
            FROM licenses l
            LEFT JOIN users u ON l.created_by_user_id = u.id
            ORDER BY l.name ASC
        `);
        return stmt.all();
    }

    static getById(id) {
        const db = getDatabase();
        const stmt = db.prepare(`
            SELECT l.*, u.username as created_by_username
            FROM licenses l
            LEFT JOIN users u ON l.created_by_user_id = u.id
            WHERE l.id = ?
        `);
        return stmt.get(id);
    }

    static create(data) {
        const db = getDatabase();
        const stmt = db.prepare(`
            INSERT INTO licenses (
                name, vendor, license_type, product_key,
                seats, purchase_date, expiry_date, cost, notes,
                sku_id, created_by_user_id
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `);
        const result = stmt.run(
            data.name,
            data.vendor || null,
            data.license_type || 'subscription',
            data.product_key || null,
            data.seats ? parseInt(data.seats) : null,
            data.purchase_date || null,
            data.expiry_date || null,
            data.cost ? parseFloat(data.cost) : null,
            data.notes || null,
            data.sku_id || null,
            data.created_by_user_id
        );
        return this.getById(result.lastInsertRowid);
    }

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

        if (data.name !== undefined) { fields.push('name = ?'); values.push(data.name); }
        if (data.vendor !== undefined) { fields.push('vendor = ?'); values.push(data.vendor || null); }
        if (data.license_type !== undefined) { fields.push('license_type = ?'); values.push(data.license_type); }
        if (data.product_key !== undefined) { fields.push('product_key = ?'); values.push(data.product_key || null); }
        if (data.seats !== undefined) { fields.push('seats = ?'); values.push(data.seats ? parseInt(data.seats) : null); }
        if (data.purchase_date !== undefined) { fields.push('purchase_date = ?'); values.push(data.purchase_date || null); }
        if (data.expiry_date !== undefined) { fields.push('expiry_date = ?'); values.push(data.expiry_date || null); }
        if (data.cost !== undefined) { fields.push('cost = ?'); values.push(data.cost ? parseFloat(data.cost) : null); }
        if (data.notes !== undefined) { fields.push('notes = ?'); values.push(data.notes || null); }
        if (data.sku_id !== undefined) { fields.push('sku_id = ?'); values.push(data.sku_id || null); }

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

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

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

    static getStatistics() {
        const db = getDatabase();
        const today = new Date().toISOString().slice(0, 10);
        const in30 = new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 10);

        const total = db.prepare('SELECT COUNT(*) as count FROM licenses').get().count;
        const expired = db.prepare(
            `SELECT COUNT(*) as count FROM licenses WHERE expiry_date IS NOT NULL AND expiry_date < ?`
        ).get(today).count;
        const expiringSoon = db.prepare(
            `SELECT COUNT(*) as count FROM licenses WHERE expiry_date IS NOT NULL AND expiry_date >= ? AND expiry_date <= ?`
        ).get(today, in30).count;

        return { total, expired, expiringSoon };
    }
}

module.exports = License;
