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

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

class Pwa_cachesDBApi extends GenericDBApi {
  static get MODEL() {
    return db.pwa_caches;
  }

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

  static get SEARCHABLE_FIELDS() {
    return ['cache_version', 'manifest_json', 'asset_list_json'];
  }

  static get RANGE_FIELDS() {
    return ['generated_at'];
  }

  static get ENUM_FIELDS() {
    return ['environment', 'is_active'];
  }

  static get CSV_FIELDS() {
    return ['id', 'environment', 'cache_version', 'is_active', 'generated_at', 'createdAt'];
  }

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

  static get ASSOCIATIONS() {
    return [
      { field: 'project', setter: 'setProject', isArray: false },
    ];
  }

  static get FIND_BY_INCLUDES() {
    return [{ association: 'project' }];
  }

  static getFieldMapping(data) {
    return {
      id: data.id || undefined,
      environment: data.environment || null,
      cache_version: data.cache_version || null,
      manifest_json: data.manifest_json || null,
      asset_list_json: data.asset_list_json || null,
      generated_at: data.generated_at || null,
      is_active: data.is_active || false,
    };
  }

  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.projects,
        as: 'project',
        where: filter.project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
      },
    ];

    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]);
      }
    }

    for (const field of this.RANGE_FIELDS) {
      const rangeKey = `${field}Range`;
      if (filter[rangeKey]) {
        const [start, end] = filter[rangeKey];
        if (start !== undefined && start !== null && start !== '') {
          where[field] = { ...where[field], [Op.gte]: start };
        }
        if (end !== undefined && end !== null && end !== '') {
          where[field] = { ...where[field], [Op.lte]: end };
        }
      }
    }

    for (const field of this.ENUM_FIELDS) {
      if (filter[field] !== undefined) {
        where[field] = filter[field];
      }
    }

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

    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 = Pwa_cachesDBApi;
