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

class DashboardPlatformsRepository {
  async _hasTable() {
    const [rows] = await pool.query(
      `SELECT 1
       FROM INFORMATION_SCHEMA.TABLES
       WHERE TABLE_SCHEMA = DATABASE()
         AND TABLE_NAME = 'dashboard_plattforms'
       LIMIT 1`
    );
    return Array.isArray(rows) && rows.length > 0;
  }

  _mapRow(row) {
    if (!row) return null;
    return {
      id: row.id,
      title: row.title,
      description: row.description ?? '',
      href: row.href,
      icon: row.icon ?? '',
      color: row.color ?? '',
      state: row.state !== 0 && row.state !== false,
      disabled: row.disabled === 1 || row.disabled === true,
      disabledText: row.disabled_text ?? null,
      sortOrder: Number.isFinite(Number(row.sort_order)) ? Number(row.sort_order) : 0,
    };
  }

  async list() {
    const has = await this._hasTable();
    if (!has) return [];

    const [rows] = await pool.query(
      `SELECT id, title, description, href, icon, color, state, disabled, disabled_text, sort_order
       FROM dashboard_plattforms
       ORDER BY sort_order ASC, title ASC`
    );
    return (rows || []).map(r => this._mapRow(r));
  }

  async listPublic() {
    const has = await this._hasTable();
    if (!has) return [];

    const [rows] = await pool.query(
      `SELECT id, title, description, href, icon, color, state, disabled, disabled_text, sort_order
       FROM dashboard_plattforms
       WHERE state = 1
       ORDER BY sort_order ASC, title ASC`
    );
    return (rows || []).map(r => this._mapRow(r));
  }

  async getById(id) {
    const has = await this._hasTable();
    if (!has) return null;

    const [rows] = await pool.query(
      `SELECT id, title, description, href, icon, color, state, disabled, disabled_text, sort_order
       FROM dashboard_plattforms
       WHERE id = ?
       LIMIT 1`,
      [id]
    );
    return this._mapRow(rows?.[0]);
  }

  async create(platform) {
    const has = await this._hasTable();
    if (!has) throw new Error('dashboard_plattforms table missing');

    await pool.query(
      `INSERT INTO dashboard_plattforms
         (id, title, description, href, icon, color, state, disabled, disabled_text, sort_order)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        platform.id,
        platform.title,
        platform.description ?? '',
        platform.href,
        platform.icon ?? '',
        platform.color ?? '',
        platform.state ? 1 : 0,
        platform.disabled ? 1 : 0,
        platform.disabledText ?? null,
        Number.isFinite(Number(platform.sortOrder)) ? Number(platform.sortOrder) : 0,
      ]
    );

    return this.getById(platform.id);
  }

  async update(id, fields) {
    const has = await this._hasTable();
    if (!has) throw new Error('dashboard_plattforms table missing');

    const [result] = await pool.query(
      `UPDATE dashboard_plattforms
       SET
         title = ?,
         description = ?,
         href = ?,
         icon = ?,
         color = ?,
         disabled = ?,
         disabled_text = ?,
         sort_order = ?
       WHERE id = ?`,
      [
        fields.title,
        fields.description ?? '',
        fields.href,
        fields.icon ?? '',
        fields.color ?? '',
        fields.disabled ? 1 : 0,
        fields.disabledText ?? null,
        Number.isFinite(Number(fields.sortOrder)) ? Number(fields.sortOrder) : 0,
        id,
      ]
    );

    if (!result?.affectedRows) return null;
    return this.getById(id);
  }

  async setState(id, state) {
    const has = await this._hasTable();
    if (!has) throw new Error('dashboard_plattforms table missing');

    const [result] = await pool.query(
      `UPDATE dashboard_plattforms SET state = ? WHERE id = ?`,
      [state ? 1 : 0, id]
    );

    if (!result?.affectedRows) return null;
    return this.getById(id);
  }
}

module.exports = DashboardPlatformsRepository;
