const pool = require('../../database/database');

class CompanySettingsRepository {
  async get() {
    const [rows] = await pool.query(
      `SELECT id, company_name, company_street, company_postal_city, company_country,
              company_logo_base64, company_logo_mime_type, updated_at
       FROM company_settings
       WHERE id = 1`
    );
    return rows[0] || null;
  }

  async update({
    company_name,
    company_street,
    company_postal_city,
    company_country,
    company_logo_base64,
    company_logo_mime_type,
  } = {}) {
    const current = await this.get();
    const next = {
      company_name: company_name !== undefined ? company_name : (current?.company_name ?? ''),
      company_street: company_street !== undefined ? company_street : (current?.company_street ?? ''),
      company_postal_city: company_postal_city !== undefined ? company_postal_city : (current?.company_postal_city ?? ''),
      company_country: company_country !== undefined ? company_country : (current?.company_country ?? ''),
      company_logo_base64: company_logo_base64 !== undefined ? (company_logo_base64 || null) : (current?.company_logo_base64 ?? null),
      company_logo_mime_type: company_logo_mime_type !== undefined ? (company_logo_mime_type || null) : (current?.company_logo_mime_type ?? null),
    };

    await pool.query(
      `INSERT INTO company_settings (
         id, company_name, company_street, company_postal_city, company_country,
         company_logo_base64, company_logo_mime_type
       )
       VALUES (1, ?, ?, ?, ?, ?, ?)
       ON DUPLICATE KEY UPDATE
         company_name = VALUES(company_name),
         company_street = VALUES(company_street),
         company_postal_city = VALUES(company_postal_city),
         company_country = VALUES(company_country),
         company_logo_base64 = VALUES(company_logo_base64),
         company_logo_mime_type = VALUES(company_logo_mime_type)`,
      [
        next.company_name || '',
        next.company_street || '',
        next.company_postal_city || '',
        next.company_country || '',
        next.company_logo_base64,
        next.company_logo_mime_type,
      ]
    );
    return this.get();
  }
}

module.exports = CompanySettingsRepository;
