const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');

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

module.exports = class ReservationsDBApi {
  static async create(data, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    const reservations = await db.reservations.create(
      {
        id: data.id || undefined,

        ref: data.ref || null,
        status_manual: data.status_manual || null,
        status_computed: data.status_computed || null,
        start_at: data.start_at || null,
        end_at: data.end_at || null,
        pickup_address: data.pickup_address || null,
        return_address: data.return_address || null,
        options: data.options || null,
        days: data.days || null,
        price_per_day: data.price_per_day || null,
        total_price: data.total_price || null,
        paid_amount: data.paid_amount || null,
        balance_amount: data.balance_amount || null,
        guarantee_method: data.guarantee_method || null,
        guarantee_amount: data.guarantee_amount || null,
        guarantee_status: data.guarantee_status || null,
        departure_validated_at: data.departure_validated_at || null,
        return_validated_at: data.return_validated_at || null,
        notes: data.notes || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await reservations.setTenant(data.tenant || null, {
      transaction,
    });

    await reservations.setClient(data.client || null, {
      transaction,
    });

    await reservations.setVehicle(data.vehicle || null, {
      transaction,
    });

    await reservations.setAgences(data.agences || null, {
      transaction,
    });

    return reservations;
  }

  static async bulkImport(data, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    // Prepare data - wrapping individual data transformations in a map() method
    const reservationsData = data.map((item, index) => ({
      id: item.id || undefined,

      ref: item.ref || null,
      status_manual: item.status_manual || null,
      status_computed: item.status_computed || null,
      start_at: item.start_at || null,
      end_at: item.end_at || null,
      pickup_address: item.pickup_address || null,
      return_address: item.return_address || null,
      options: item.options || null,
      days: item.days || null,
      price_per_day: item.price_per_day || null,
      total_price: item.total_price || null,
      paid_amount: item.paid_amount || null,
      balance_amount: item.balance_amount || null,
      guarantee_method: item.guarantee_method || null,
      guarantee_amount: item.guarantee_amount || null,
      guarantee_status: item.guarantee_status || null,
      departure_validated_at: item.departure_validated_at || null,
      return_validated_at: item.return_validated_at || null,
      notes: item.notes || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * 1000),
    }));

    // Bulk create items
    const reservations = await db.reservations.bulkCreate(reservationsData, {
      transaction,
    });

    // For each item created, replace relation files

    return reservations;
  }

  static async update(id, data, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;
    const globalAccess = currentUser.app_role?.globalAccess;

    const reservations = await db.reservations.findByPk(
      id,
      {},
      { transaction },
    );

    const updatePayload = {};

    if (data.ref !== undefined) updatePayload.ref = data.ref;

    if (data.status_manual !== undefined)
      updatePayload.status_manual = data.status_manual;

    if (data.status_computed !== undefined)
      updatePayload.status_computed = data.status_computed;

    if (data.start_at !== undefined) updatePayload.start_at = data.start_at;

    if (data.end_at !== undefined) updatePayload.end_at = data.end_at;

    if (data.pickup_address !== undefined)
      updatePayload.pickup_address = data.pickup_address;

    if (data.return_address !== undefined)
      updatePayload.return_address = data.return_address;

    if (data.options !== undefined) updatePayload.options = data.options;

    if (data.days !== undefined) updatePayload.days = data.days;

    if (data.price_per_day !== undefined)
      updatePayload.price_per_day = data.price_per_day;

    if (data.total_price !== undefined)
      updatePayload.total_price = data.total_price;

    if (data.paid_amount !== undefined)
      updatePayload.paid_amount = data.paid_amount;

    if (data.balance_amount !== undefined)
      updatePayload.balance_amount = data.balance_amount;

    if (data.guarantee_method !== undefined)
      updatePayload.guarantee_method = data.guarantee_method;

    if (data.guarantee_amount !== undefined)
      updatePayload.guarantee_amount = data.guarantee_amount;

    if (data.guarantee_status !== undefined)
      updatePayload.guarantee_status = data.guarantee_status;

    if (data.departure_validated_at !== undefined)
      updatePayload.departure_validated_at = data.departure_validated_at;

    if (data.return_validated_at !== undefined)
      updatePayload.return_validated_at = data.return_validated_at;

    if (data.notes !== undefined) updatePayload.notes = data.notes;

    updatePayload.updatedById = currentUser.id;

    await reservations.update(updatePayload, { transaction });

    if (data.tenant !== undefined) {
      await reservations.setTenant(
        data.tenant,

        { transaction },
      );
    }

    if (data.client !== undefined) {
      await reservations.setClient(
        data.client,

        { transaction },
      );
    }

    if (data.vehicle !== undefined) {
      await reservations.setVehicle(
        data.vehicle,

        { transaction },
      );
    }

    if (data.agences !== undefined) {
      await reservations.setAgences(
        data.agences,

        { transaction },
      );
    }

    return reservations;
  }

  static async deleteByIds(ids, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    const reservations = await db.reservations.findAll({
      where: {
        id: {
          [Op.in]: ids,
        },
      },
      transaction,
    });

    await db.sequelize.transaction(async (transaction) => {
      for (const record of reservations) {
        await record.update({ deletedBy: currentUser.id }, { transaction });
      }
      for (const record of reservations) {
        await record.destroy({ transaction });
      }
    });

    return reservations;
  }

  static async remove(id, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    const reservations = await db.reservations.findByPk(id, options);

    await reservations.update(
      {
        deletedBy: currentUser.id,
      },
      {
        transaction,
      },
    );

    await reservations.destroy({
      transaction,
    });

    return reservations;
  }

  static async findBy(where, options) {
    const transaction = (options && options.transaction) || undefined;

    const reservations = await db.reservations.findOne(
      { where },
      { transaction },
    );

    if (!reservations) {
      return reservations;
    }

    const output = reservations.get({ plain: true });

    output.claims_reservation = await reservations.getClaims_reservation({
      transaction,
    });

    output.drivers_reservation = await reservations.getDrivers_reservation({
      transaction,
    });

    output.guarantees_reservation =
      await reservations.getGuarantees_reservation({
        transaction,
      });

    output.infractions_reservation =
      await reservations.getInfractions_reservation({
        transaction,
      });

    output.payments_reservation = await reservations.getPayments_reservation({
      transaction,
    });

    output.vehicle_conditions_reservation =
      await reservations.getVehicle_conditions_reservation({
        transaction,
      });

    output.tenant = await reservations.getTenant({
      transaction,
    });

    output.client = await reservations.getClient({
      transaction,
    });

    output.vehicle = await reservations.getVehicle({
      transaction,
    });

    output.agences = await reservations.getAgences({
      transaction,
    });

    return output;
  }

  static async findAll(filter, globalAccess, options) {
    const limit = filter.limit || 0;
    let offset = 0;
    let where = {};
    const currentPage = +filter.page;

    const user = (options && options.currentUser) || null;
    const userAgences = (user && user.agences?.id) || null;

    if (userAgences) {
      if (options?.currentUser?.agencesId) {
        where.agencesId = options.currentUser.agencesId;
      }
    }

    offset = currentPage * limit;

    const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [
      {
        model: db.tenants,
        as: 'tenant',

        where: filter.tenant
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.tenant
                      .split('|')
                      .map((term) => Utils.uuid(term)),
                  },
                },
                {
                  name: {
                    [Op.or]: filter.tenant
                      .split('|')
                      .map((term) => ({ [Op.iLike]: `%${term}%` })),
                  },
                },
              ],
            }
          : {},
      },

      {
        model: db.clients,
        as: 'client',

        where: filter.client
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.client
                      .split('|')
                      .map((term) => Utils.uuid(term)),
                  },
                },
                {
                  first_name: {
                    [Op.or]: filter.client
                      .split('|')
                      .map((term) => ({ [Op.iLike]: `%${term}%` })),
                  },
                },
              ],
            }
          : {},
      },

      {
        model: db.vehicles,
        as: 'vehicle',

        where: filter.vehicle
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.vehicle
                      .split('|')
                      .map((term) => Utils.uuid(term)),
                  },
                },
                {
                  plate_number: {
                    [Op.or]: filter.vehicle
                      .split('|')
                      .map((term) => ({ [Op.iLike]: `%${term}%` })),
                  },
                },
              ],
            }
          : {},
      },

      {
        model: db.agences,
        as: 'agences',
      },
    ];

    if (filter) {
      if (filter.id) {
        where = {
          ...where,
          ['id']: Utils.uuid(filter.id),
        };
      }

      if (filter.ref) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('reservations', 'ref', filter.ref),
        };
      }

      if (filter.pickup_address) {
        where = {
          ...where,
          [Op.and]: Utils.ilike(
            'reservations',
            'pickup_address',
            filter.pickup_address,
          ),
        };
      }

      if (filter.return_address) {
        where = {
          ...where,
          [Op.and]: Utils.ilike(
            'reservations',
            'return_address',
            filter.return_address,
          ),
        };
      }

      if (filter.options) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('reservations', 'options', filter.options),
        };
      }

      if (filter.notes) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('reservations', 'notes', filter.notes),
        };
      }

      if (filter.calendarStart && filter.calendarEnd) {
        where = {
          ...where,
          [Op.or]: [
            {
              start_at: {
                [Op.between]: [filter.calendarStart, filter.calendarEnd],
              },
            },
            {
              end_at: {
                [Op.between]: [filter.calendarStart, filter.calendarEnd],
              },
            },
          ],
        };
      }

      if (filter.start_atRange) {
        const [start, end] = filter.start_atRange;

        if (start !== undefined && start !== null && start !== '') {
          where = {
            ...where,
            start_at: {
              ...where.start_at,
              [Op.gte]: start,
            },
          };
        }

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            start_at: {
              ...where.start_at,
              [Op.lte]: end,
            },
          };
        }
      }

      if (filter.end_atRange) {
        const [start, end] = filter.end_atRange;

        if (start !== undefined && start !== null && start !== '') {
          where = {
            ...where,
            end_at: {
              ...where.end_at,
              [Op.gte]: start,
            },
          };
        }

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            end_at: {
              ...where.end_at,
              [Op.lte]: end,
            },
          };
        }
      }

      if (filter.daysRange) {
        const [start, end] = filter.daysRange;

        if (start !== undefined && start !== null && start !== '') {
          where = {
            ...where,
            days: {
              ...where.days,
              [Op.gte]: start,
            },
          };
        }

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            days: {
              ...where.days,
              [Op.lte]: end,
            },
          };
        }
      }

      if (filter.price_per_dayRange) {
        const [start, end] = filter.price_per_dayRange;

        if (start !== undefined && start !== null && start !== '') {
          where = {
            ...where,
            price_per_day: {
              ...where.price_per_day,
              [Op.gte]: start,
            },
          };
        }

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            price_per_day: {
              ...where.price_per_day,
              [Op.lte]: end,
            },
          };
        }
      }

      if (filter.total_priceRange) {
        const [start, end] = filter.total_priceRange;

        if (start !== undefined && start !== null && start !== '') {
          where = {
            ...where,
            total_price: {
              ...where.total_price,
              [Op.gte]: start,
            },
          };
        }

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            total_price: {
              ...where.total_price,
              [Op.lte]: end,
            },
          };
        }
      }

      if (filter.paid_amountRange) {
        const [start, end] = filter.paid_amountRange;

        if (start !== undefined && start !== null && start !== '') {
          where = {
            ...where,
            paid_amount: {
              ...where.paid_amount,
              [Op.gte]: start,
            },
          };
        }

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            paid_amount: {
              ...where.paid_amount,
              [Op.lte]: end,
            },
          };
        }
      }

      if (filter.balance_amountRange) {
        const [start, end] = filter.balance_amountRange;

        if (start !== undefined && start !== null && start !== '') {
          where = {
            ...where,
            balance_amount: {
              ...where.balance_amount,
              [Op.gte]: start,
            },
          };
        }

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            balance_amount: {
              ...where.balance_amount,
              [Op.lte]: end,
            },
          };
        }
      }

      if (filter.guarantee_amountRange) {
        const [start, end] = filter.guarantee_amountRange;

        if (start !== undefined && start !== null && start !== '') {
          where = {
            ...where,
            guarantee_amount: {
              ...where.guarantee_amount,
              [Op.gte]: start,
            },
          };
        }

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            guarantee_amount: {
              ...where.guarantee_amount,
              [Op.lte]: end,
            },
          };
        }
      }

      if (filter.departure_validated_atRange) {
        const [start, end] = filter.departure_validated_atRange;

        if (start !== undefined && start !== null && start !== '') {
          where = {
            ...where,
            departure_validated_at: {
              ...where.departure_validated_at,
              [Op.gte]: start,
            },
          };
        }

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            departure_validated_at: {
              ...where.departure_validated_at,
              [Op.lte]: end,
            },
          };
        }
      }

      if (filter.return_validated_atRange) {
        const [start, end] = filter.return_validated_atRange;

        if (start !== undefined && start !== null && start !== '') {
          where = {
            ...where,
            return_validated_at: {
              ...where.return_validated_at,
              [Op.gte]: start,
            },
          };
        }

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            return_validated_at: {
              ...where.return_validated_at,
              [Op.lte]: end,
            },
          };
        }
      }

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

      if (filter.status_manual) {
        where = {
          ...where,
          status_manual: filter.status_manual,
        };
      }

      if (filter.status_computed) {
        where = {
          ...where,
          status_computed: filter.status_computed,
        };
      }

      if (filter.guarantee_method) {
        where = {
          ...where,
          guarantee_method: filter.guarantee_method,
        };
      }

      if (filter.guarantee_status) {
        where = {
          ...where,
          guarantee_status: filter.guarantee_status,
        };
      }

      if (filter.agences) {
        const listItems = filter.agences.split('|').map((item) => {
          return Utils.uuid(item);
        });

        where = {
          ...where,
          agencesId: { [Op.or]: listItems },
        };
      }

      if (filter.createdAtRange) {
        const [start, end] = filter.createdAtRange;

        if (start !== undefined && start !== null && start !== '') {
          where = {
            ...where,
            ['createdAt']: {
              ...where.createdAt,
              [Op.gte]: start,
            },
          };
        }

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            ['createdAt']: {
              ...where.createdAt,
              [Op.lte]: end,
            },
          };
        }
      }
    }

    if (globalAccess) {
      delete where.agencesId;
    }

    const queryOptions = {
      where,
      include,
      distinct: true,
      order:
        filter.field && filter.sort
          ? [[filter.field, filter.sort]]
          : [['createdAt', 'desc']],
      transaction: options?.transaction,
      logging: console.log,
    };

    if (!options?.countOnly) {
      queryOptions.limit = limit ? Number(limit) : undefined;
      queryOptions.offset = offset ? Number(offset) : undefined;
    }

    try {
      const { rows, count } = await db.reservations.findAndCountAll(
        queryOptions,
      );

      return {
        rows: options?.countOnly ? [] : rows,
        count: count,
      };
    } catch (error) {
      console.error('Error executing query:', error);
      throw error;
    }
  }

  static async findAllAutocomplete(
    query,
    limit,
    offset,
    globalAccess,
    organizationId,
  ) {
    let where = {};

    if (!globalAccess && organizationId) {
      where.organizationId = organizationId;
    }

    if (query) {
      where = {
        [Op.or]: [
          { ['id']: Utils.uuid(query) },
          Utils.ilike('reservations', 'ref', query),
        ],
      };
    }

    const records = await db.reservations.findAll({
      attributes: ['id', 'ref'],
      where,
      limit: limit ? Number(limit) : undefined,
      offset: offset ? Number(offset) : undefined,
      orderBy: [['ref', 'ASC']],
    });

    return records.map((record) => ({
      id: record.id,
      label: record.ref,
    }));
  }
};
