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

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

        exam_date: data.exam_date || null,
        max_marks: data.max_marks || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await exam_subjects.setExam(data.exam || null, {
      transaction,
    });

    await exam_subjects.setSubject(data.subject || null, {
      transaction,
    });

    await exam_subjects.setSchools(data.schools || null, {
      transaction,
    });

    return exam_subjects;
  }

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

      exam_date: item.exam_date || null,
      max_marks: item.max_marks || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * 1000),
    }));

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

    // For each item created, replace relation files

    return exam_subjects;
  }

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

    const updatePayload = {};

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.exam !== undefined) {
      await exam_subjects.setExam(
        data.exam,

        { transaction },
      );
    }

    if (data.subject !== undefined) {
      await exam_subjects.setSubject(
        data.subject,

        { transaction },
      );
    }

    if (data.schools !== undefined) {
      await exam_subjects.setSchools(
        data.schools,

        { transaction },
      );
    }

    return exam_subjects;
  }

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

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

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

    return exam_subjects;
  }

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

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

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

    await exam_subjects.destroy({
      transaction,
    });

    return exam_subjects;
  }

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

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

    if (!exam_subjects) {
      return exam_subjects;
    }

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

    output.marks_exam_subject = await exam_subjects.getMarks_exam_subject({
      transaction,
    });

    output.exam = await exam_subjects.getExam({
      transaction,
    });

    output.subject = await exam_subjects.getSubject({
      transaction,
    });

    output.schools = await exam_subjects.getSchools({
      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 userSchools = (user && user.schools?.id) || null;

    if (userSchools) {
      if (options?.currentUser?.schoolsId) {
        where.schoolsId = options.currentUser.schoolsId;
      }
    }

    offset = currentPage * limit;

    const orderBy = null;

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

    let include = [
      {
        model: db.exams,
        as: 'exam',

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

      {
        model: db.subjects,
        as: 'subject',

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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