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 VehiclesDBApi {
  static async create(data, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

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

        plate_number: data.plate_number || null,
        brand: data.brand || null,
        model: data.model || null,
        year: data.year || null,
        color: data.color || null,
        category: data.category || null,
        fuel_type: data.fuel_type || null,
        transmission: data.transmission || null,
        mileage: data.mileage || null,
        daily_price: data.daily_price || null,
        status: data.status || null,
        insurance_expiry: data.insurance_expiry || null,
        tech_visit_expiry: data.tech_visit_expiry || null,
        photos: data.photos || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

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

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

    return vehicles;
  }

  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 vehiclesData = data.map((item, index) => ({
      id: item.id || undefined,

      plate_number: item.plate_number || null,
      brand: item.brand || null,
      model: item.model || null,
      year: item.year || null,
      color: item.color || null,
      category: item.category || null,
      fuel_type: item.fuel_type || null,
      transmission: item.transmission || null,
      mileage: item.mileage || null,
      daily_price: item.daily_price || null,
      status: item.status || null,
      insurance_expiry: item.insurance_expiry || null,
      tech_visit_expiry: item.tech_visit_expiry || null,
      photos: item.photos || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * 1000),
    }));

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

    // For each item created, replace relation files

    return vehicles;
  }

  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 vehicles = await db.vehicles.findByPk(id, {}, { transaction });

    const updatePayload = {};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

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

        { transaction },
      );
    }

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

        { transaction },
      );
    }

    return vehicles;
  }

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

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

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

    return vehicles;
  }

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

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

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

    await vehicles.destroy({
      transaction,
    });

    return vehicles;
  }

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

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

    if (!vehicles) {
      return vehicles;
    }

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

    output.expenses_vehicle = await vehicles.getExpenses_vehicle({
      transaction,
    });

    output.infractions_vehicle = await vehicles.getInfractions_vehicle({
      transaction,
    });

    output.maintenance_vehicle = await vehicles.getMaintenance_vehicle({
      transaction,
    });

    output.reservations_vehicle = await vehicles.getReservations_vehicle({
      transaction,
    });

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

    output.agences = await vehicles.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.agences,
        as: 'agences',
      },
    ];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      if (filter.status) {
        where = {
          ...where,
          status: filter.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.vehicles.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('vehicles', 'plate_number', query),
        ],
      };
    }

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

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