const db = require('../../database/database');
const { logger } = require('../../middleware/logger');

class CompanyStampRepository {
  async create(data, conn) {
    logger.info('CompanyStampRepository.create:start', { company_id: data.company_id, label: data.label });
    const q = `
      INSERT INTO company_stamps (company_id, label, mime_type, image_base64, is_active, created_at, updated_at)
      VALUES (?, ?, ?, ?, ?, NOW(), NOW())
    `;
    const params = [data.company_id, data.label || null, data.mime_type, data.image_base64, !!data.is_active];
    const executor = conn || db;
    // Avoid array-destructuring; support both [result, fields] and plain result
    const execResult = await executor.execute(q, params);
    const res = Array.isArray(execResult) ? execResult[0] : execResult;
    const id = res && typeof res.insertId !== 'undefined' ? res.insertId : null;
    logger.info('CompanyStampRepository.create:success', { id });
    return { id, ...data };
  }

  async findById(id, conn) {
    const q = `SELECT * FROM company_stamps WHERE id = ? LIMIT 1`;
    const executor = conn || db;
    const [rows] = await executor.execute(q, [id]);
    return rows[0] || null;
  }

  async findByCompanyId(companyId, conn) {
    const q = `SELECT * FROM company_stamps WHERE company_id = ? ORDER BY created_at DESC`;
    const executor = conn || db;
    const [rows] = await executor.execute(q, [companyId]);
    return rows;
  }

  async findActiveByCompanyId(companyId, conn) {
    const q = `SELECT * FROM company_stamps WHERE company_id = ? AND is_active = 1 LIMIT 1`;
    const executor = conn || db;
    const [rows] = await executor.execute(q, [companyId]);
    return rows[0] || null;
  }

  async deactivateAllForCompany(companyId, conn) {
    const q = `UPDATE company_stamps SET is_active = 0, updated_at = NOW() WHERE company_id = ? AND is_active = 1`;
    const executor = conn || db;
    await executor.execute(q, [companyId]);
  }

  async activate(id, companyId, conn) {
    const q = `UPDATE company_stamps SET is_active = 1, updated_at = NOW() WHERE id = ? AND company_id = ?`;
    const executor = conn || db;
    await executor.execute(q, [id, companyId]);
  }

  async delete(id, companyId, conn) {
    const q = `DELETE FROM company_stamps WHERE id = ? AND company_id = ?`;
    const executor = conn || db;
    // Avoid array-destructuring; support both [result, fields] and plain result
    const execResult = await executor.execute(q, [id, companyId]);
    const res = Array.isArray(execResult) ? execResult[0] : execResult;

    // Lightweight log of result shape to verify driver behavior
    try {
      logger.debug
        ? logger.debug('CompanyStampRepository.delete:result_shape', {
            isArray: Array.isArray(execResult),
            keys: Array.isArray(execResult) ? Object.keys(execResult[0] || {}) : Object.keys(execResult || {})
          })
        : logger.info('CompanyStampRepository.delete:result_shape', {
            isArray: Array.isArray(execResult),
            keys: Array.isArray(execResult) ? Object.keys(execResult[0] || {}) : Object.keys(execResult || {})
          });
    } catch (_) {
      // no-op logging fallback
    }

    const affected = res && typeof res.affectedRows === 'number' ? res.affectedRows : 0;
    return affected > 0;
  }

  async listAll(conn) {
    const q = `SELECT * FROM company_stamps ORDER BY created_at DESC`;
    const executor = conn || db;
    const [rows] = await executor.execute(q);
    return rows;
  }
}

module.exports = new CompanyStampRepository();
