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

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

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

    return schools;
  }

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

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

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

    // For each item created, replace relation files

    return schools;
  }

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

    const updatePayload = {};

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

    updatePayload.updatedById = currentUser.id;

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

    return schools;
  }

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

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

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

    return schools;
  }

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

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

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

    await schools.destroy({
      transaction,
    });

    return schools;
  }

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

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

    if (!schools) {
      return schools;
    }

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

    output.users_schools = await schools.getUsers_schools({
      transaction,
    });

    output.activity_logs_schools = await schools.getActivity_logs_schools({
      transaction,
    });

    output.assignment_submissions_schools =
      await schools.getAssignment_submissions_schools({
        transaction,
      });

    output.assignments_schools = await schools.getAssignments_schools({
      transaction,
    });

    output.bills_school = await schools.getBills_school({
      transaction,
    });

    output.bills_schools = await schools.getBills_schools({
      transaction,
    });

    output.class_messages_schools = await schools.getClass_messages_schools({
      transaction,
    });

    output.class_subjects_schools = await schools.getClass_subjects_schools({
      transaction,
    });

    output.classes_school = await schools.getClasses_school({
      transaction,
    });

    output.classes_schools = await schools.getClasses_schools({
      transaction,
    });

    output.exam_subjects_schools = await schools.getExam_subjects_schools({
      transaction,
    });

    output.exams_school = await schools.getExams_school({
      transaction,
    });

    output.exams_schools = await schools.getExams_schools({
      transaction,
    });

    output.fee_payments_schools = await schools.getFee_payments_schools({
      transaction,
    });

    output.fee_structures_school = await schools.getFee_structures_school({
      transaction,
    });

    output.fee_structures_schools = await schools.getFee_structures_schools({
      transaction,
    });

    output.lesson_plans_schools = await schools.getLesson_plans_schools({
      transaction,
    });

    output.login_logs_schools = await schools.getLogin_logs_schools({
      transaction,
    });

    output.marks_schools = await schools.getMarks_schools({
      transaction,
    });

    output.messages_school = await schools.getMessages_school({
      transaction,
    });

    output.messages_schools = await schools.getMessages_schools({
      transaction,
    });

    output.parents_schools = await schools.getParents_schools({
      transaction,
    });

    output.period_settings_school = await schools.getPeriod_settings_school({
      transaction,
    });

    output.period_settings_schools = await schools.getPeriod_settings_schools({
      transaction,
    });

    output.school_admins_school = await schools.getSchool_admins_school({
      transaction,
    });

    output.school_admins_schools = await schools.getSchool_admins_schools({
      transaction,
    });

    output.student_attendance_schools =
      await schools.getStudent_attendance_schools({
        transaction,
      });

    output.students_school = await schools.getStudents_school({
      transaction,
    });

    output.students_schools = await schools.getStudents_schools({
      transaction,
    });

    output.subjects_school = await schools.getSubjects_school({
      transaction,
    });

    output.subjects_schools = await schools.getSubjects_schools({
      transaction,
    });

    output.teacher_attendance_school =
      await schools.getTeacher_attendance_school({
        transaction,
      });

    output.teacher_attendance_schools =
      await schools.getTeacher_attendance_schools({
        transaction,
      });

    output.teachers_school = await schools.getTeachers_school({
      transaction,
    });

    output.teachers_schools = await schools.getTeachers_schools({
      transaction,
    });

    output.timetables_schools = await schools.getTimetables_schools({
      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 = [];

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

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

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

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

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

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