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

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

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

    await marks.setStudent(data.student || null, {
      transaction,
    });

    await marks.setExam_subject(data.exam_subject || null, {
      transaction,
    });

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

    return marks;
  }

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

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

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

    // For each item created, replace relation files

    return marks;
  }

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

    const updatePayload = {};

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.student !== undefined) {
      await marks.setStudent(
        data.student,

        { transaction },
      );
    }

    if (data.exam_subject !== undefined) {
      await marks.setExam_subject(
        data.exam_subject,

        { transaction },
      );
    }

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

        { transaction },
      );
    }

    return marks;
  }

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

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

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

    return marks;
  }

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

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

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

    await marks.destroy({
      transaction,
    });

    return marks;
  }

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

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

    if (!marks) {
      return marks;
    }

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

    output.student = await marks.getStudent({
      transaction,
    });

    output.exam_subject = await marks.getExam_subject({
      transaction,
    });

    output.schools = await marks.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.students,
        as: 'student',

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

      {
        model: db.exam_subjects,
        as: 'exam_subject',

        where: filter.exam_subject
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.exam_subject
                      .split('|')
                      .map((term) => Utils.uuid(term)),
                  },
                },
                {
                  subject: {
                    [Op.or]: filter.exam_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.marks_obtainedRange) {
        const [start, end] = filter.marks_obtainedRange;

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

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            marks_obtained: {
              ...where.marks_obtained,
              [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.marks.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('marks', 'marks_obtained', query),
        ],
      };
    }

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

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