const GenericDBApi = require('./base.api');
const db = require('../models');
const Utils = require('../utils');
const {
  applyRuntimeEnvironment,
  applyRuntimeProjectFilter,
} = require('./runtime-context');

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

class TransitionsDBApi extends GenericDBApi {
  static get MODEL() {
    return db.transitions;
  }

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

  static get SEARCHABLE_FIELDS() {
    return ['source_key', 'name', 'slug', 'video_url', 'audio_url'];
  }

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

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

  static get CSV_FIELDS() {
    return ['id', 'source_key', 'name', 'slug', 'video_url', 'audio_url', 'duration_sec', 'createdAt'];
  }

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

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

  static getFieldMapping(data) {
    return {
      id: data.id || undefined,
      environment: data.environment || null,
      source_key: data.source_key || null,
      name: data.name || null,
      slug: data.slug || null,
      video_url: data.video_url || null,
      audio_url: data.audio_url || null,
      supports_reverse: data.supports_reverse || false,
      duration_sec: data.duration_sec || null,
    };
  }

  static async findBy(where, options = {}) {
    const transaction = options.transaction;
    const queryWhere = applyRuntimeEnvironment({ ...where }, options);
    const projectInclude = applyRuntimeProjectFilter(
      { model: db.projects, as: 'project' },
      options
    );

    const record = await this.MODEL.findOne({
      where: queryWhere,
      transaction,
      include: [
        projectInclude,
        { association: 'page_links_transition' },
      ],
    });

    if (!record) return null;
    return record.get({ plain: true });
  }

  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}%` }))
              }
            },
          ]
        } : {},
      },
    ];

    include[0] = applyRuntimeProjectFilter(include[0], options);

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

    where = applyRuntimeEnvironment(where, options);

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