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

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

        slug: data.slug || null,
        title: data.title || null,
        bio: data.bio || null,
        status: data.status || null,
        published_at: data.published_at || null,
        og_title: data.og_title || null,
        og_description: data.og_description || null,
        og_image_url: data.og_image_url || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await profile_pages.setUser(data.user || null, {
      transaction,
    });

    await profile_pages.setTheme_template(data.theme_template || null, {
      transaction,
    });

    await profile_pages.setOrganizations(data.organizations || null, {
      transaction,
    });

    return profile_pages;
  }

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

      slug: item.slug || null,
      title: item.title || null,
      bio: item.bio || null,
      status: item.status || null,
      published_at: item.published_at || null,
      og_title: item.og_title || null,
      og_description: item.og_description || null,
      og_image_url: item.og_image_url || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * 1000),
    }));

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

    // For each item created, replace relation files

    return profile_pages;
  }

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

    const updatePayload = {};

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

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

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

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

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.user !== undefined) {
      await profile_pages.setUser(
        data.user,

        { transaction },
      );
    }

    if (data.theme_template !== undefined) {
      await profile_pages.setTheme_template(
        data.theme_template,

        { transaction },
      );
    }

    if (data.organizations !== undefined) {
      await profile_pages.setOrganizations(
        data.organizations,

        { transaction },
      );
    }

    return profile_pages;
  }

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

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

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

    return profile_pages;
  }

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

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

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

    await profile_pages.destroy({
      transaction,
    });

    return profile_pages;
  }

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

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

    if (!profile_pages) {
      return profile_pages;
    }

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

    output.analytics_daily_profile_page =
      await profile_pages.getAnalytics_daily_profile_page({
        transaction,
      });

    output.analytics_events_profile_page =
      await profile_pages.getAnalytics_events_profile_page({
        transaction,
      });

    output.blocks_profile_page = await profile_pages.getBlocks_profile_page({
      transaction,
    });

    output.domain_mappings_profile_page =
      await profile_pages.getDomain_mappings_profile_page({
        transaction,
      });

    output.flags_profile_page = await profile_pages.getFlags_profile_page({
      transaction,
    });

    output.user = await profile_pages.getUser({
      transaction,
    });

    output.theme_template = await profile_pages.getTheme_template({
      transaction,
    });

    output.organizations = await profile_pages.getOrganizations({
      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 userOrganizations = (user && user.organizations?.id) || null;

    if (userOrganizations) {
      if (options?.currentUser?.organizationsId) {
        where.organizationsId = options.currentUser.organizationsId;
      }
    }

    offset = currentPage * limit;

    const orderBy = null;

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

    let include = [
      {
        model: db.users,
        as: 'user',

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

      {
        model: db.templates,
        as: 'theme_template',

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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