const GenericDBApi = require('./base.api');
const db = require('../models');
const Utils = require('../utils');

const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

class RolesDBApi extends GenericDBApi {
  static get MODEL() {
    return db.roles;
  }

  static get TABLE_NAME() {
    return 'roles';
  }

  static get SEARCHABLE_FIELDS() {
    return ['name', 'role_customization'];
  }

  static get RANGE_FIELDS() {
    return [];
  }

  static get ENUM_FIELDS() {
    return [];
  }

  static get CSV_FIELDS() {
    return ['id', 'name', 'role_customization', 'createdAt'];
  }

  static get AUTOCOMPLETE_FIELD() {
    return 'name';
  }

  static get ASSOCIATIONS() {
    return [
      { field: 'permissions', setter: 'setPermissions', isArray: true },
    ];
  }

  static get FIND_BY_INCLUDES() {
    return [
      { association: 'users_app_role' },
      { association: 'permissions' },
    ];
  }

  static getFieldMapping(data) {
    return {
      id: data.id || undefined,
      name: data.name || null,
      role_customization: data.role_customization || null,
    };
  }

  static async findAll(filter = {}, options = {}) {
    filter = filter || {};
    const limit = filter.limit || 0;
    const currentPage = +filter.page || 0;
    const offset = currentPage * limit;

    let where = {};

    let include = [
      {
        model: db.permissions,
        as: 'permissions',
        required: false,
      },
    ];

    if (filter.id) {
      where.id = Utils.uuid(filter.id);
    }

    for (const field of this.SEARCHABLE_FIELDS) {
      if (filter[field]) {
        where[Op.and] = Utils.ilike(this.TABLE_NAME, field, filter[field]);
      }
    }

    if (filter.active !== undefined) {
      where.active = filter.active === true || filter.active === 'true';
    }

    if (filter.permissions) {
      const searchTerms = filter.permissions.split('|');
      include = [
        {
          model: db.permissions,
          as: 'permissions_filter',
          required: searchTerms.length > 0,
          where: searchTerms.length > 0 ? {
            [Op.or]: [
              { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
              {
                name: {
                  [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                }
              }
            ]
          } : undefined
        },
        ...include,
      ];
    }

    if (filter.createdAtRange) {
      const [start, end] = filter.createdAtRange;
      if (start !== undefined && start !== null && start !== '') {
        where.createdAt = { ...where.createdAt, [Op.gte]: start };
      }
      if (end !== undefined && end !== null && end !== '') {
        where.createdAt = { ...where.createdAt, [Op.lte]: end };
      }
    }

    const queryOptions = {
      where,
      include,
      distinct: true,
      order: filter.field && filter.sort
        ? [[filter.field, filter.sort]]
        : [['createdAt', 'desc']],
      transaction: options.transaction,
    };

    if (!options.countOnly) {
      queryOptions.limit = limit ? Number(limit) : undefined;
      queryOptions.offset = offset ? Number(offset) : undefined;
    }

    try {
      const { rows, count } = await this.MODEL.findAndCountAll(queryOptions);
      return {
        rows: options.countOnly ? [] : rows,
        count,
      };
    } catch (error) {
      console.error('Error executing query:', error);
      throw error;
    }
  }
}

module.exports = RolesDBApi;
