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

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

class Presigned_url_requestsDBApi extends GenericDBApi {
  static get MODEL() {
    return db.presigned_url_requests;
  }

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

  static get SEARCHABLE_FIELDS() {
    return ['requested_key', 'mime_type', 'status'];
  }

  static get RANGE_FIELDS() {
    return ['requested_size_mb', 'expires_at'];
  }

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

  static get CSV_FIELDS() {
    return ['id', 'purpose', 'asset_type', 'requested_key', 'mime_type', 'status', 'createdAt'];
  }

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

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

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

  static getFieldMapping(data) {
    return {
      id: data.id || undefined,
      purpose: data.purpose || null,
      asset_type: data.asset_type || null,
      requested_key: data.requested_key || null,
      mime_type: data.mime_type || null,
      requested_size_mb: data.requested_size_mb || null,
      expires_at: data.expires_at || null,
      status: data.status || 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.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}%` }))
              }
            },
          ]
        } : {},
      },
      {
        model: db.users,
        as: 'user',
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.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 = Presigned_url_requestsDBApi;
