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

class AssetInspection {
    /**
     * Create the asset_inspections table if it doesn't exist
     */
    static migrate() {
        const db = getDatabase();
        db.prepare(`
            CREATE TABLE IF NOT EXISTS asset_inspections (
                id                    INTEGER PRIMARY KEY AUTOINCREMENT,
                asset_id              INTEGER NOT NULL REFERENCES assets(id) ON DELETE CASCADE,
                inspected_by_user_id  INTEGER REFERENCES users(id) ON DELETE SET NULL,
                inspection_date       DATE NOT NULL,
                result                TEXT CHECK(result IN ('bestanden', 'nicht_bestanden')) NOT NULL,
                notes                 TEXT,
                next_due_date         DATE,
                created_at            DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        `).run();
    }

    /**
     * Create a new inspection record
     */
    static create({ asset_id, inspected_by_user_id, inspection_date, result, notes, next_due_date }) {
        const db = getDatabase();
        const stmt = db.prepare(`
            INSERT INTO asset_inspections
                (asset_id, inspected_by_user_id, inspection_date, result, notes, next_due_date)
            VALUES
                (?, ?, ?, ?, ?, ?)
        `);
        const info = stmt.run(
            asset_id,
            inspected_by_user_id || null,
            inspection_date,
            result,
            notes || null,
            next_due_date || null
        );
        return this.getById(info.lastInsertRowid);
    }

    /**
     * Get a single inspection by ID
     */
    static getById(id) {
        const db = getDatabase();
        return db.prepare(`
            SELECT ai.*, u.username AS inspector_name
            FROM asset_inspections ai
            LEFT JOIN users u ON ai.inspected_by_user_id = u.id
            WHERE ai.id = ?
        `).get(id);
    }

    /**
     * Get all inspections for a given asset, newest first
     */
    static getByAsset(assetId) {
        const db = getDatabase();
        return db.prepare(`
            SELECT ai.*, u.username AS inspector_name
            FROM asset_inspections ai
            LEFT JOIN users u ON ai.inspected_by_user_id = u.id
            WHERE ai.asset_id = ?
            ORDER BY ai.inspection_date DESC, ai.created_at DESC
        `).all(assetId);
    }
}

module.exports = AssetInspection;
