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

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

class Asset_variantsDBApi extends GenericDBApi {
  static get MODEL() {
    return db.asset_variants;
  }

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

  static get SEARCHABLE_FIELDS() {
    return ['cdn_url'];
  }

  static get RANGE_FIELDS() {
    return ['width_px', 'height_px', 'size_mb'];
  }

  static get ENUM_FIELDS() {
    return ['variant_type'];
  }

  static get CSV_FIELDS() {
    return ['id', 'variant_type', 'cdn_url', 'width_px', 'height_px', 'size_mb', 'createdAt'];
  }

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

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

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

  static getFieldMapping(data) {
    return {
      id: data.id || undefined,
      variant_type: data.variant_type || null,
      cdn_url: data.cdn_url || null,
      width_px: data.width_px || null,
      height_px: data.height_px || null,
      size_mb: data.size_mb || 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.assets,
        as: 'asset',
        where: filter.asset ? {
          [Op.or]: [
            { id: { [Op.in]: filter.asset.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.asset.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 = Asset_variantsDBApi;
