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

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

        name: data.name || null,
        rate_card_import: data.rate_card_import || false,

        client_fixed_text: data.client_fixed_text || null,
        yes_fixed_text: data.yes_fixed_text || null,
        default_client_contact: data.default_client_contact || null,
        inherit_default_rate_card: data.inherit_default_rate_card || false,

        default_costs: data.default_costs || null,
        production_fee: data.production_fee || null,
        insurance_fee: data.insurance_fee || null,
        temp: data.temp || null,
        xero_id: data.xero_id || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

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

    await brands.setDefault_account_manager(
      data.default_account_manager || null,
      {
        transaction,
      },
    );

    await brands.setDefault_sales(data.default_sales || null, {
      transaction,
    });

    await brands.setLink_rate_card(data.link_rate_card || null, {
      transaction,
    });

    return brands;
  }

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

      name: item.name || null,
      rate_card_import: item.rate_card_import || false,

      client_fixed_text: item.client_fixed_text || null,
      yes_fixed_text: item.yes_fixed_text || null,
      default_client_contact: item.default_client_contact || null,
      inherit_default_rate_card: item.inherit_default_rate_card || false,

      default_costs: item.default_costs || null,
      production_fee: item.production_fee || null,
      insurance_fee: item.insurance_fee || null,
      temp: item.temp || 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 brands = await db.brands.bulkCreate(brandsData, { transaction });

    // For each item created, replace relation files

    return brands;
  }

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

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

    const updatePayload = {};

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

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

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

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

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

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

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

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

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

        { transaction },
      );
    }

    if (data.default_account_manager !== undefined) {
      await brands.setDefault_account_manager(
        data.default_account_manager,

        { transaction },
      );
    }

    if (data.default_sales !== undefined) {
      await brands.setDefault_sales(
        data.default_sales,

        { transaction },
      );
    }

    if (data.link_rate_card !== undefined) {
      await brands.setLink_rate_card(
        data.link_rate_card,

        { transaction },
      );
    }

    return brands;
  }

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

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

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

    return brands;
  }

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

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

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

    await brands.destroy({
      transaction,
    });

    return brands;
  }

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

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

    if (!brands) {
      return brands;
    }

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

    output.brand_rate_cards_brand = await brands.getBrand_rate_cards_brand({
      transaction,
    });

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

    output.default_account_manager = await brands.getDefault_account_manager({
      transaction,
    });

    output.default_sales = await brands.getDefault_sales({
      transaction,
    });

    output.link_rate_card = await brands.getLink_rate_card({
      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.clients,
        as: 'client',

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

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

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

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

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

      {
        model: db.brand_rate_cards,
        as: 'link_rate_card',

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

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

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

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

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

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

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

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

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

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

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            default_costs: {
              ...where.default_costs,
              [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.rate_card_import) {
        where = {
          ...where,
          rate_card_import: filter.rate_card_import,
        };
      }

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

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

    const records = await db.brands.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,
    }));
  }
};
