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

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

        name: data.name || null,
        tc_number: data.tc_number || null,
        tax_number: data.tax_number || null,
        insurance_number: data.insurance_number || null,
        phone: data.phone || null,
        sector: data.sector || null,
        registration_date: data.registration_date || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await partners.setKooperatif(data.kooperatif || null, {
      transaction,
    });

    return partners;
  }

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

      name: item.name || null,
      tc_number: item.tc_number || null,
      tax_number: item.tax_number || null,
      insurance_number: item.insurance_number || null,
      phone: item.phone || null,
      sector: item.sector || null,
      registration_date: item.registration_date || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * 1000),
    }));

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

    // For each item created, replace relation files

    return partners;
  }

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

    const updatePayload = {};

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

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

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

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.kooperatif !== undefined) {
      await partners.setKooperatif(
        data.kooperatif,

        { transaction },
      );
    }

    return partners;
  }

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

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

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

    return partners;
  }

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

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

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

    await partners.destroy({
      transaction,
    });

    return partners;
  }

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

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

    if (!partners) {
      return partners;
    }

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

    output.accounts_partner = await partners.getAccounts_partner({
      transaction,
    });

    output.barter_offers_partner = await partners.getBarter_offers_partner({
      transaction,
    });

    output.delayed_payments_partner =
      await partners.getDelayed_payments_partner({
        transaction,
      });

    output.loan_applications_partner =
      await partners.getLoan_applications_partner({
        transaction,
      });

    output.projects_partner = await partners.getProjects_partner({
      transaction,
    });

    output.kooperatif = await partners.getKooperatif({
      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 userKooperatif = (user && user.kooperatif?.id) || null;

    if (userKooperatif) {
      if (options?.currentUser?.kooperatifId) {
        where.kooperatifId = options.currentUser.kooperatifId;
      }
    }

    offset = currentPage * limit;

    const orderBy = null;

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

    let include = [
      {
        model: db.kooperatif,
        as: 'kooperatif',
      },
    ];

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

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

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

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

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

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

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

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

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

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

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

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

        where = {
          ...where,
          kooperatifId: { [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.kooperatifId;
    }

    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.partners.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('partners', 'name', query),
        ],
      };
    }

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

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