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

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

class AssetsDBApi extends GenericDBApi {
  static get MODEL() {
    return db.assets;
  }

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

  static get SEARCHABLE_FIELDS() {
    return ['name', 'cdn_url', 'storage_key', 'mime_type', 'checksum'];
  }

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

  static get ENUM_FIELDS() {
    return ['asset_type', 'type', 'is_public'];
  }

  static get CSV_FIELDS() {
    return ['id', 'name', 'asset_type', 'type', 'cdn_url', 'storage_key', 'mime_type', 'size_mb', 'createdAt'];
  }

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

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

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

  static get RELATION_FILTERS() {
    return [
      { filterKey: 'project', model: db.projects, as: 'project', searchField: 'name' },
    ];
  }

  static getFieldMapping(data) {
    return {
      id: data.id || undefined,
      name: data.name || null,
      asset_type: data.asset_type || null,
      type: data.type || 'general',
      cdn_url: data.cdn_url || null,
      storage_key: data.storage_key || null,
      mime_type: data.mime_type || null,
      size_mb: data.size_mb || null,
      width_px: data.width_px || null,
      height_px: data.height_px || null,
      duration_sec: data.duration_sec || null,
      checksum: data.checksum || null,
      is_public: data.is_public || 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 = AssetsDBApi;
