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

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

        thyme_id: data.thyme_id || null,
        name: data.name || null,
        office: data.office || null,
        address: data.address || null,
        city: data.city || null,
        post_code: data.post_code || null,
        country_txt: data.country_txt || null,
        phone_number: data.phone_number || null,
        website: data.website || null,
        currency: data.currency || null,
        curious_customer_id: data.curious_customer_id || null,
        agency: data.agency || null,
        inclusive_amends: data.inclusive_amends || false,

        early_payment_discount: data.early_payment_discount || null,
        client_id_link: data.client_id_link || null,
        public_url: data.public_url || null,
        production_fee: data.production_fee || null,
        insurance_fee: data.insurance_fee || null,
        xero_id: data.xero_id || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await clients.setCountry(data.country || null, {
      transaction,
    });

    await clients.setAccount_manager(data.account_manager || null, {
      transaction,
    });

    await clients.setAll_brands(data.all_brands || [], {
      transaction,
    });

    return clients;
  }

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

      thyme_id: item.thyme_id || null,
      name: item.name || null,
      office: item.office || null,
      address: item.address || null,
      city: item.city || null,
      post_code: item.post_code || null,
      country_txt: item.country_txt || null,
      phone_number: item.phone_number || null,
      website: item.website || null,
      currency: item.currency || null,
      curious_customer_id: item.curious_customer_id || null,
      agency: item.agency || null,
      inclusive_amends: item.inclusive_amends || false,

      early_payment_discount: item.early_payment_discount || null,
      client_id_link: item.client_id_link || null,
      public_url: item.public_url || null,
      production_fee: item.production_fee || null,
      insurance_fee: item.insurance_fee || null,
      xero_id: item.xero_id || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * 1000),
    }));

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

    // For each item created, replace relation files

    return clients;
  }

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

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

    const updatePayload = {};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.country !== undefined) {
      await clients.setCountry(
        data.country,

        { transaction },
      );
    }

    if (data.account_manager !== undefined) {
      await clients.setAccount_manager(
        data.account_manager,

        { transaction },
      );
    }

    if (data.all_brands !== undefined) {
      await clients.setAll_brands(data.all_brands, { transaction });
    }

    return clients;
  }

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

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

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

    return clients;
  }

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

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

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

    await clients.destroy({
      transaction,
    });

    return clients;
  }

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

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

    if (!clients) {
      return clients;
    }

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

    output.brands_client = await clients.getBrands_client({
      transaction,
    });

    output.brand_rate_cards_client = await clients.getBrand_rate_cards_client({
      transaction,
    });

    output.country = await clients.getCountry({
      transaction,
    });

    output.account_manager = await clients.getAccount_manager({
      transaction,
    });

    output.all_brands = await clients.getAll_brands({
      transaction,
    });

    return output;
  }

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

    offset = currentPage * limit;

    const orderBy = null;

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

    let include = [
      {
        model: db.countries,
        as: 'country',

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

      {
        model: db.users,
        as: 'account_manager',

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

      {
        model: db.brands,
        as: 'all_brands',
        required: false,
      },
    ];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      if (filter.all_brands) {
        const searchTerms = filter.all_brands.split('|');

        include = [
          {
            model: db.brands,
            as: 'all_brands_filter',
            required: searchTerms.length > 0,
            where:
              searchTerms.length > 0
                ? {
                    [Op.or]: [
                      {
                        id: {
                          [Op.in]: searchTerms.map((term) => Utils.uuid(term)),
                        },
                      },
                      {
                        id: {
                          [Op.or]: searchTerms.map((term) => ({
                            [Op.iLike]: `%${term}%`,
                          })),
                        },
                      },
                    ],
                  }
                : undefined,
          },
          ...include,
        ];
      }

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

    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.clients.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) {
    let where = {};

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

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

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