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

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

        full_name: data.full_name || null,
        dob: data.dob || null,
        gender: data.gender || null,
        admission_date: data.admission_date || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

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

    await students.setSchool(data.school || null, {
      transaction,
    });

    await students.setParent(data.parent || null, {
      transaction,
    });

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

    return students;
  }

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

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

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

    // For each item created, replace relation files

    return students;
  }

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

    const updatePayload = {};

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

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

        { transaction },
      );
    }

    if (data.school !== undefined) {
      await students.setSchool(
        data.school,

        { transaction },
      );
    }

    if (data.parent !== undefined) {
      await students.setParent(
        data.parent,

        { transaction },
      );
    }

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

        { transaction },
      );
    }

    return students;
  }

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

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

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

    return students;
  }

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

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

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

    await students.destroy({
      transaction,
    });

    return students;
  }

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

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

    if (!students) {
      return students;
    }

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

    output.assignment_submissions_student =
      await students.getAssignment_submissions_student({
        transaction,
      });

    output.fee_payments_student = await students.getFee_payments_student({
      transaction,
    });

    output.marks_student = await students.getMarks_student({
      transaction,
    });

    output.student_attendance_student =
      await students.getStudent_attendance_student({
        transaction,
      });

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

    output.school = await students.getSchool({
      transaction,
    });

    output.parent = await students.getParent({
      transaction,
    });

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

      {
        model: db.parents,
        as: 'parent',

        where: filter.parent
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.parent
                      .split('|')
                      .map((term) => Utils.uuid(term)),
                  },
                },
                {
                  full_name: {
                    [Op.or]: filter.parent
                      .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.full_name) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('students', 'full_name', filter.full_name),
        };
      }

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

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

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

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

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

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

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

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

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

        where = {
          ...where,
          schoolId: { [Op.or]: listItems },
        };
      }

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

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

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