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 { ClassEnrollments } from '@/db/models/class_enrollments';
import type { CurrentUser, DbApiOptions } from '@/db/api/types';

type ClassEnrollmentsData = Partial<
  InferCreationAttributes<ClassEnrollments>
> & {
  organization?: string | null;
  class?: string | null;
  student?: string | null;
};

interface ClassEnrollmentsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  class?: string;
  student?: string;
  enrolled_onRange?: Array<string | null | undefined>;
  ended_onRange?: Array<string | null | undefined>;
  active?: boolean | string;
  status?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class Class_enrollmentsDBApi {
  static async create(
    data: ClassEnrollmentsData,
    options?: DbApiOptions,
  ): Promise<ClassEnrollments> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const class_enrollments = await db.class_enrollments.create(
      {
        id: data.id || undefined,
        enrolled_on: data.enrolled_on || null,
        ended_on: data.ended_on || null,
        status: data.status || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await class_enrollments.setOrganization(
      currentUser.organizationId ?? undefined,
      { transaction },
    );
    await class_enrollments.setClass(data.class ?? undefined, { transaction });

    return class_enrollments;
  }

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

    const class_enrollmentsData = data.map((item, index) => ({
      id: item.id || undefined,
      enrolled_on: item.enrolled_on || null,
      ended_on: item.ended_on || 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.class_enrollments.bulkCreate(class_enrollmentsData, {
      transaction,
    });
  }

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

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

    if (!class_enrollments) {
      return null;
    }

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.organization !== undefined) {
      const orgId = globalAccess
        ? data.organization
        : currentUser.organizationId;
      await class_enrollments.setOrganization(orgId ?? undefined, {
        transaction,
      });
    }
    if (data.class !== undefined) {
      await class_enrollments.setClass(data.class ?? undefined, {
        transaction,
      });
    }

    return class_enrollments;
  }

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

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

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

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

    if (!class_enrollments) {
      return null;
    }

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

    const [organization, class_] = await Promise.all([
      class_enrollments.getOrganization({ transaction }),
      class_enrollments.getClass({ transaction }),
    ]);
    output.organization = organization;
    output.class = class_;

    return output;
  }

  static async findAll(
    filter: ClassEnrollmentsFilter,
    globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<{ rows: ClassEnrollments[]; 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.classes,
        as: 'class',
        where: filter.class
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.class.split('|').map((t) => Utils.uuid(t)),
                  },
                },
                {
                  name: {
                    [Op.or]: filter.class
                      .split('|')
                      .map((t) => ({ [Op.iLike]: `%${t}%` })),
                  },
                },
              ],
            }
          : {},
      },
    ];

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.enrolled_onRange) {
      const [start, end] = filter.enrolled_onRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, enrolled_on: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          enrolled_on: {
            ...(typeof where.enrolled_on === 'object' ? where.enrolled_on : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.ended_onRange) {
      const [start, end] = filter.ended_onRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, ended_on: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          ended_on: {
            ...(typeof where.ended_on === 'object' ? where.ended_on : {}),
            [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.class_enrollments.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.class_enrollments,
      'status',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default Class_enrollmentsDBApi;
