const MailTemplateRepository = require('../../repositories/template/MailTemplateRepository');

class MailTemplateService {
  _requiredString(value, fieldName) {
    const parsed = String(value == null ? '' : value).trim();
    if (!parsed) {
      const error = new Error(`${fieldName} is required`);
      error.status = 400;
      throw error;
    }
    return parsed;
  }

  _optionalString(value) {
    if (value === undefined || value === null) return null;
    const parsed = String(value).trim();
    return parsed || null;
  }

  _toBool(value, fallback = false) {
    if (value === undefined || value === null) return fallback;
    if (typeof value === 'boolean') return value;
    const normalized = String(value).trim().toLowerCase();
    if (['1', 'true', 'yes', 'on'].includes(normalized)) return true;
    if (['0', 'false', 'no', 'off'].includes(normalized)) return false;
    return fallback;
  }

  async list(query = {}) {
    return MailTemplateRepository.list({
      includeArchived: this._toBool(query.includeArchived, false),
      templateType: this._optionalString(query.templateType),
    });
  }

  async getById(id) {
    const numericId = Number(id);
    if (!Number.isFinite(numericId) || numericId <= 0) {
      const error = new Error('Invalid id');
      error.status = 400;
      throw error;
    }

    return MailTemplateRepository.getById(numericId);
  }

  async create(payload = {}, userId = null) {
    const template_type = this._requiredString(payload.template_type, 'template_type');
    const name = this._requiredString(payload.name, 'name');
    const html_content = this._requiredString(payload.html_content, 'html_content');

    return MailTemplateRepository.create({
      template_type,
      name,
      subject: this._optionalString(payload.subject),
      html_content,
      userId,
    });
  }

  async update(id, payload = {}, userId = null) {
    const numericId = Number(id);
    if (!Number.isFinite(numericId) || numericId <= 0) {
      const error = new Error('Invalid id');
      error.status = 400;
      throw error;
    }

    const updatePayload = {};

    if (Object.prototype.hasOwnProperty.call(payload, 'template_type')) {
      updatePayload.template_type = this._requiredString(payload.template_type, 'template_type');
    }
    if (Object.prototype.hasOwnProperty.call(payload, 'name')) {
      updatePayload.name = this._requiredString(payload.name, 'name');
    }
    if (Object.prototype.hasOwnProperty.call(payload, 'subject')) {
      updatePayload.subject = this._optionalString(payload.subject);
    }
    if (Object.prototype.hasOwnProperty.call(payload, 'html_content')) {
      updatePayload.html_content = this._requiredString(payload.html_content, 'html_content');
    }

    updatePayload.userId = userId;
    return MailTemplateRepository.update(numericId, updatePayload);
  }

  async activate(id, userId = null) {
    const numericId = Number(id);
    if (!Number.isFinite(numericId) || numericId <= 0) {
      const error = new Error('Invalid id');
      error.status = 400;
      throw error;
    }

    return MailTemplateRepository.activate(numericId, userId);
  }

  async archive(id, userId = null) {
    const numericId = Number(id);
    if (!Number.isFinite(numericId) || numericId <= 0) {
      const error = new Error('Invalid id');
      error.status = 400;
      throw error;
    }

    return MailTemplateRepository.archive(numericId, userId);
  }

  async unarchive(id, userId = null) {
    const numericId = Number(id);
    if (!Number.isFinite(numericId) || numericId <= 0) {
      const error = new Error('Invalid id');
      error.status = 400;
      throw error;
    }

    return MailTemplateRepository.unarchive(numericId, userId);
  }

  async remove(id) {
    const numericId = Number(id);
    if (!Number.isFinite(numericId) || numericId <= 0) {
      const error = new Error('Invalid id');
      error.status = 400;
      throw error;
    }

    return MailTemplateRepository.delete(numericId);
  }
}

module.exports = new MailTemplateService();
