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

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

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

    await lesson_plans.setTeacher(data.teacher || null, {
      transaction,
    });

    await lesson_plans.setSubject(data.subject || null, {
      transaction,
    });

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

    return lesson_plans;
  }

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

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

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

    // For each item created, replace relation files

    return lesson_plans;
  }

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

    const updatePayload = {};

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

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.teacher !== undefined) {
      await lesson_plans.setTeacher(
        data.teacher,

        { transaction },
      );
    }

    if (data.subject !== undefined) {
      await lesson_plans.setSubject(
        data.subject,

        { transaction },
      );
    }

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

        { transaction },
      );
    }

    return lesson_plans;
  }

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

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

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

    return lesson_plans;
  }

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

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

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

    await lesson_plans.destroy({
      transaction,
    });

    return lesson_plans;
  }

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

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

    if (!lesson_plans) {
      return lesson_plans;
    }

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

    output.teacher = await lesson_plans.getTeacher({
      transaction,
    });

    output.subject = await lesson_plans.getSubject({
      transaction,
    });

    output.schools = await lesson_plans.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.teachers,
        as: 'teacher',

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

      {
        model: db.subjects,
        as: 'subject',

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

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

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

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

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

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

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

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

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