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

const DEFAULT_DESIGN = {
    brand_name:    'CEREDA SYSTEMS',
    brand_subtitle:'IT Support',
    brand_icon:    '💻',
    logo_url:      '',
    primary_color: '#0d9488',
    button_color:  '#0d9488',
    bg_color:      '#f1f5f9',
    company_name:  'Cereda Systems GmbH',
    footer_text:   'Automatisch generiert von IT Nexus · Bitte nicht direkt antworten.',
};

const ALLOWED_FIELDS = Object.keys(DEFAULT_DESIGN);

class EmailDesign {
    static migrate() {
        const db = getDatabase();
        db.exec(`
            CREATE TABLE IF NOT EXISTS email_design (
                id            INTEGER PRIMARY KEY DEFAULT 1,
                brand_name    TEXT NOT NULL DEFAULT 'CEREDA SYSTEMS',
                brand_subtitle TEXT NOT NULL DEFAULT 'IT Support',
                brand_icon    TEXT NOT NULL DEFAULT '💻',
                logo_url      TEXT NOT NULL DEFAULT '',
                primary_color TEXT NOT NULL DEFAULT '#0d9488',
                button_color  TEXT NOT NULL DEFAULT '#0d9488',
                bg_color      TEXT NOT NULL DEFAULT '#f1f5f9',
                company_name  TEXT NOT NULL DEFAULT 'Cereda Systems GmbH',
                footer_text   TEXT NOT NULL DEFAULT 'Automatisch generiert von IT Nexus · Bitte nicht direkt antworten.'
            );
        `);
        db.prepare('INSERT OR IGNORE INTO email_design (id) VALUES (1)').run();
    }

    static getDesign() {
        try {
            const row = getDatabase().prepare('SELECT * FROM email_design WHERE id = 1').get();
            return row ? { ...DEFAULT_DESIGN, ...row } : { ...DEFAULT_DESIGN };
        } catch (_) {
            return { ...DEFAULT_DESIGN };
        }
    }

    static updateDesign(fields) {
        const updates = Object.entries(fields).filter(([k]) => ALLOWED_FIELDS.includes(k));
        if (!updates.length) return EmailDesign.getDesign();
        const db = getDatabase();
        const sql = `UPDATE email_design SET ${updates.map(([k]) => `${k}=?`).join(',')} WHERE id=1`;
        db.prepare(sql).run(...updates.map(([, v]) => v));
        return EmailDesign.getDesign();
    }

    static reset() {
        const db = getDatabase();
        db.prepare(`
            UPDATE email_design SET
                brand_name=?, brand_subtitle=?, brand_icon=?, logo_url=?,
                primary_color=?, button_color=?, bg_color=?, company_name=?, footer_text=?
            WHERE id=1
        `).run(
            DEFAULT_DESIGN.brand_name, DEFAULT_DESIGN.brand_subtitle, DEFAULT_DESIGN.brand_icon,
            DEFAULT_DESIGN.logo_url, DEFAULT_DESIGN.primary_color, DEFAULT_DESIGN.button_color,
            DEFAULT_DESIGN.bg_color, DEFAULT_DESIGN.company_name, DEFAULT_DESIGN.footer_text
        );
        return EmailDesign.getDesign();
    }
}

module.exports = { EmailDesign, DEFAULT_DESIGN };
