import {
  Op,
  type InferAttributes,
  type InferCreationAttributes,
  type WhereAttributeHash,
} from 'sequelize';
import db from '@/db/models';
import {
  removeRecord,
  deleteRecordsByIds,
  autocompleteByField,
} 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 { Organizations } from '@/db/models/organizations';
import type { CurrentUser, DbApiOptions } from '@/db/api/types';

type OrganizationsData = Partial<InferCreationAttributes<Organizations>>;

interface OrganizationsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  name?: string;
  active?: boolean | string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class OrganizationsDBApi {
  static async create(
    data: OrganizationsData,
    options?: DbApiOptions,
  ): Promise<Organizations> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    return db.organizations.create(
      {
        id: data.id || undefined,
        name: data.name || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );
  }

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

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

    return db.organizations.bulkCreate(organizationsData, { transaction });
  }

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

    const organizations = await db.organizations.findByPk(id, { transaction });

    if (!organizations) {
      return null;
    }

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

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

    updatePayload.updatedById = currentUser.id;

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

    return organizations;
  }

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

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

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

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

    if (!organizations) {
      return null;
    }

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

    const [
      users_organizations,
      campuses_organization,
      academic_years_organization,
      grades_organization,
      subjects_organization,
      staff_organization,
      classes_organization,
      class_enrollments_organization,
      class_subjects_organization,
      timetables_organization,
      timetable_periods_organization,
      attendance_sessions_organization,
      attendance_records_organization,
      assessments_organization,
      assessment_results_organization,
      messages_organization,
      message_recipients_organization,
    ] = await Promise.all([
      organizations.getUsers_organizations({ transaction }),
      organizations.getCampuses_organization({ transaction }),
      organizations.getAcademic_years_organization({ transaction }),
      organizations.getGrades_organization({ transaction }),
      organizations.getSubjects_organization({ transaction }),
      organizations.getStaff_organization({ transaction }),
      organizations.getClasses_organization({ transaction }),
      organizations.getClass_enrollments_organization({ transaction }),
      organizations.getClass_subjects_organization({ transaction }),
      organizations.getTimetables_organization({ transaction }),
      organizations.getTimetable_periods_organization({ transaction }),
      organizations.getAttendance_sessions_organization({ transaction }),
      organizations.getAttendance_records_organization({ transaction }),
      organizations.getAssessments_organization({ transaction }),
      organizations.getAssessment_results_organization({ transaction }),
      organizations.getMessages_organization({ transaction }),
      organizations.getMessage_recipients_organization({ transaction }),
    ]);
    output.users_organizations = users_organizations;
    output.campuses_organization = campuses_organization;
    output.academic_years_organization = academic_years_organization;
    output.grades_organization = grades_organization;
    output.subjects_organization = subjects_organization;
    output.staff_organization = staff_organization;
    output.classes_organization = classes_organization;
    output.class_enrollments_organization = class_enrollments_organization;
    output.class_subjects_organization = class_subjects_organization;
    output.timetables_organization = timetables_organization;
    output.timetable_periods_organization = timetable_periods_organization;
    output.attendance_sessions_organization = attendance_sessions_organization;
    output.attendance_records_organization = attendance_records_organization;
    output.assessments_organization = assessments_organization;
    output.assessment_results_organization = assessment_results_organization;
    output.messages_organization = messages_organization;
    output.message_recipients_organization = message_recipients_organization;

    return output;
  }

  static async findAll(
    filter: OrganizationsFilter,
    globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<{ rows: Organizations[]; 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;
    }

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.name) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('organizations', 'name', filter.name),
      };
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    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.organizations.findAndCountAll({
      where,
      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.organizations,
      'name',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default OrganizationsDBApi;
