import {
  Op,
  type Includeable,
  type InferAttributes,
  type InferCreationAttributes,
  type WhereAttributeHash,
} from 'sequelize';
import db from '@/db/models';
import {
  removeRecord,
  deleteRecordsByIds,
  autocompleteByField,
  findOwnedByPk,
  tenantWhere,
} from '@/db/api/shared/repository';
import { BULK_IMPORT_TIMESTAMP_STEP_MS } from '@/shared/constants/database';
import { resolvePagination } from '@/shared/constants/pagination';
import Utils from '@/db/utils';
import type { Classes } from '@/db/models/classes';
import type { CurrentUser, DbApiOptions } from '@/db/api/types';

type ClassesData = Partial<InferCreationAttributes<Classes>> & {
  organization?: string | null;
  campus?: string | null;
  academic_year?: string | null;
  grade?: string | null;
  homeroom_teacher?: string | null;
};

interface ClassesFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  name?: string;
  section?: string;
  capacityRange?: Array<number | string | null | undefined>;
  active?: boolean | string;
  status?: string;
  campus?: string;
  academic_year?: string;
  grade?: string;
  homeroom_teacher?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class ClassesDBApi {
  static async create(
    data: ClassesData,
    options?: DbApiOptions,
  ): Promise<Classes> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const classes = await db.classes.create(
      {
        id: data.id || undefined,
        name: data.name || null,
        section: data.section || null,
        capacity: data.capacity || null,
        status: data.status || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await classes.setOrganization(currentUser.organizationId ?? undefined, {
      transaction,
    });
    await classes.setCampus(data.campus ?? undefined, { transaction });
    await classes.setAcademic_year(data.academic_year ?? undefined, {
      transaction,
    });
    await classes.setGrade(data.grade ?? undefined, { transaction });
    await classes.setHomeroom_teacher(data.homeroom_teacher ?? undefined, {
      transaction,
    });

    return classes;
  }

  static async bulkImport(
    data: ClassesData[],
    options?: DbApiOptions,
  ): Promise<Classes[]> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const classesData = data.map((item, index) => ({
      id: item.id || undefined,
      name: item.name || null,
      section: item.section || null,
      capacity: item.capacity || null,
      status: item.status || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * BULK_IMPORT_TIMESTAMP_STEP_MS),
    }));

    return db.classes.bulkCreate(classesData, { transaction });
  }

  static async update(
    id: string,
    data: ClassesData,
    options?: DbApiOptions,
  ): Promise<Classes | null> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;
    const globalAccess = currentUser.app_role?.globalAccess;

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

    if (!classes) {
      return null;
    }

    const updatePayload: Partial<InferAttributes<Classes>> = {};

    if (data.name !== undefined) updatePayload.name = data.name;
    if (data.section !== undefined) updatePayload.section = data.section;
    if (data.capacity !== undefined) updatePayload.capacity = data.capacity;
    if (data.status !== undefined) updatePayload.status = data.status;

    updatePayload.updatedById = currentUser.id;

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

    if (data.organization !== undefined) {
      const orgId = globalAccess
        ? data.organization
        : currentUser.organizationId;
      await classes.setOrganization(orgId ?? undefined, { transaction });
    }
    if (data.campus !== undefined) {
      await classes.setCampus(data.campus ?? undefined, { transaction });
    }
    if (data.academic_year !== undefined) {
      await classes.setAcademic_year(data.academic_year ?? undefined, {
        transaction,
      });
    }
    if (data.grade !== undefined) {
      await classes.setGrade(data.grade ?? undefined, { transaction });
    }
    if (data.homeroom_teacher !== undefined) {
      await classes.setHomeroom_teacher(data.homeroom_teacher ?? undefined, {
        transaction,
      });
    }

    return classes;
  }

  static async deleteByIds(
    ids: string[],
    options?: DbApiOptions,
  ): Promise<Classes[]> {
    return deleteRecordsByIds(db.classes, ids, options);
  }

  static async remove(
    id: string,
    options?: DbApiOptions,
  ): Promise<Classes | null> {
    return removeRecord(db.classes, id, options);
  }

  static async findBy(
    where: WhereAttributeHash,
    options?: DbApiOptions,
  ): Promise<Record<string, unknown> | null> {
    const transaction = options?.transaction;

    const classes = await db.classes.findOne({
      where: { ...where, ...tenantWhere(options?.currentUser) },
      transaction,
    });

    if (!classes) {
      return null;
    }

    const output: Record<string, unknown> = classes.get({ plain: true });

    const [
      class_enrollments_class,
      class_subjects_class,
      attendance_sessions_class,
      organization,
      campus,
      academic_year,
      grade,
      homeroom_teacher,
    ] = await Promise.all([
      classes.getClass_enrollments_class({ transaction }),
      classes.getClass_subjects_class({ transaction }),
      classes.getAttendance_sessions_class({ transaction }),
      classes.getOrganization({ transaction }),
      classes.getCampus({ transaction }),
      classes.getAcademic_year({ transaction }),
      classes.getGrade({ transaction }),
      classes.getHomeroom_teacher({ transaction }),
    ]);
    output.class_enrollments_class = class_enrollments_class;
    output.class_subjects_class = class_subjects_class;
    output.attendance_sessions_class = attendance_sessions_class;
    output.organization = organization;
    output.campus = campus;
    output.academic_year = academic_year;
    output.grade = grade;
    output.homeroom_teacher = homeroom_teacher;

    return output;
  }

  static async findAll(
    filter: ClassesFilter,
    globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<{ rows: Classes[]; count: number }> {
    const { limit, offset } = resolvePagination(filter.limit, filter.page);

    let where: WhereAttributeHash = {};

    const userOrganizations = options?.currentUser?.organizations?.id ?? null;
    if (userOrganizations && options?.currentUser?.organizationId) {
      where.organizationId = options.currentUser.organizationId;
    }

    const include: Includeable[] = [
      { model: db.organizations, as: 'organization' },
      {
        model: db.campuses,
        as: 'campus',
        where: filter.campus
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.campus.split('|').map((t) => Utils.uuid(t)),
                  },
                },
                {
                  name: {
                    [Op.or]: filter.campus
                      .split('|')
                      .map((t) => ({ [Op.iLike]: `%${t}%` })),
                  },
                },
              ],
            }
          : {},
      },
      {
        model: db.academic_years,
        as: 'academic_year',
        where: filter.academic_year
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.academic_year
                      .split('|')
                      .map((t) => Utils.uuid(t)),
                  },
                },
                {
                  name: {
                    [Op.or]: filter.academic_year
                      .split('|')
                      .map((t) => ({ [Op.iLike]: `%${t}%` })),
                  },
                },
              ],
            }
          : {},
      },
      {
        model: db.grades,
        as: 'grade',
        where: filter.grade
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.grade.split('|').map((t) => Utils.uuid(t)),
                  },
                },
                {
                  name: {
                    [Op.or]: filter.grade
                      .split('|')
                      .map((t) => ({ [Op.iLike]: `%${t}%` })),
                  },
                },
              ],
            }
          : {},
      },
      {
        model: db.staff,
        as: 'homeroom_teacher',
        where: filter.homeroom_teacher
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.homeroom_teacher
                      .split('|')
                      .map((t) => Utils.uuid(t)),
                  },
                },
                {
                  employee_number: {
                    [Op.or]: filter.homeroom_teacher
                      .split('|')
                      .map((t) => ({ [Op.iLike]: `%${t}%` })),
                  },
                },
              ],
            }
          : {},
      },
    ];

    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.capacityRange) {
      const [start, end] = filter.capacityRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, capacity: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          capacity: {
            ...(typeof where.capacity === 'object' ? where.capacity : {}),
            [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.organization) {
      const listItems = filter.organization
        .split('|')
        .map((item) => Utils.uuid(item));
      where = { ...where, organizationId: { [Op.or]: listItems } };
    }
    if (filter.createdAtRange) {
      const [start, end] = filter.createdAtRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, createdAt: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          createdAt: {
            ...(typeof where.createdAt === 'object' ? where.createdAt : {}),
            [Op.lte]: end,
          },
        };
      }
    }

    if (globalAccess) {
      delete where.organizationId;
    }

    const order: [string, string][] =
      filter.field && filter.sort
        ? [[filter.field, filter.sort]]
        : [['createdAt', 'desc']];

    const { rows, count } = await db.classes.findAndCountAll({
      where,
      include,
      distinct: true,
      order,
      transaction: options?.transaction,
      limit: !options?.countOnly && limit ? limit : undefined,
      offset: !options?.countOnly && offset ? offset : undefined,
    });

    return { rows: options?.countOnly ? [] : rows, count };
  }

  static async findAllAutocomplete(
    query: string | undefined,
    limit: number | undefined,
    offset: number | undefined,
    globalAccess: boolean,
    organizationId: string | undefined,
  ): Promise<Array<{ id: string; label: string | null }>> {
    return autocompleteByField(
      db.classes,
      'name',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default ClassesDBApi;
