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

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

        submission_date: data.submission_date || null,
        content: data.content || null,
        grade: data.grade || null,
        feedback: data.feedback || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await assignment_submissions.setAssignment(data.assignment || null, {
      transaction,
    });

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

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

    return assignment_submissions;
  }

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

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

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

    // For each item created, replace relation files

    return assignment_submissions;
  }

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

    const updatePayload = {};

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.assignment !== undefined) {
      await assignment_submissions.setAssignment(
        data.assignment,

        { transaction },
      );
    }

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

        { transaction },
      );
    }

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

        { transaction },
      );
    }

    return assignment_submissions;
  }

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

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

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

    return assignment_submissions;
  }

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

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

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

    await assignment_submissions.destroy({
      transaction,
    });

    return assignment_submissions;
  }

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

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

    if (!assignment_submissions) {
      return assignment_submissions;
    }

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

    output.assignment = await assignment_submissions.getAssignment({
      transaction,
    });

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

    output.schools = await assignment_submissions.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.assignments,
        as: 'assignment',

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

      {
        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.schools,
        as: 'schools',
      },
    ];

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

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

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

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

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

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

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

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

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

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

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