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

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

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

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

    await classes.setClass_teacher(data.class_teacher || null, {
      transaction,
    });

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

    return classes;
  }

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

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

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

    // For each item created, replace relation files

    return classes;
  }

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

    const updatePayload = {};

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

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

    updatePayload.updatedById = currentUser.id;

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

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

        { transaction },
      );
    }

    if (data.class_teacher !== undefined) {
      await classes.setClass_teacher(
        data.class_teacher,

        { transaction },
      );
    }

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

        { transaction },
      );
    }

    return classes;
  }

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

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

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

    return classes;
  }

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

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

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

    await classes.destroy({
      transaction,
    });

    return classes;
  }

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

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

    if (!classes) {
      return classes;
    }

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

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

    output.class_teacher = await classes.getClass_teacher({
      transaction,
    });

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

      {
        model: db.teachers,
        as: 'class_teacher',

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

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

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

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

    const records = await db.classes.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,
    }));
  }
};
