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

type AttendanceSessionsData = Partial<
  InferCreationAttributes<AttendanceSessions>
> & {
  organization?: string | null;
  campus?: string | null;
  class?: string | null;
  class_subject?: string | null;
  taken_by?: string | null;
};

interface AttendanceSessionsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  notes?: string;
  session_dateRange?: Array<string | null | undefined>;
  active?: boolean | string;
  session_type?: string;
  campus?: string;
  class?: string;
  class_subject?: string;
  taken_by?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class Attendance_sessionsDBApi {
  static async create(
    data: AttendanceSessionsData,
    options?: DbApiOptions,
  ): Promise<AttendanceSessions> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const attendance_sessions = await db.attendance_sessions.create(
      {
        id: data.id || undefined,
        session_date: data.session_date || null,
        session_type: data.session_type || null,
        notes: data.notes || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await attendance_sessions.setOrganization(
      currentUser.organizationId ?? undefined,
      { transaction },
    );
    await attendance_sessions.setCampus(data.campus ?? undefined, {
      transaction,
    });
    await attendance_sessions.setClass(data.class ?? undefined, { transaction });
    await attendance_sessions.setClass_subject(data.class_subject ?? undefined, {
      transaction,
    });
    await attendance_sessions.setTaken_by(data.taken_by ?? undefined, {
      transaction,
    });

    return attendance_sessions;
  }

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

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

    return db.attendance_sessions.bulkCreate(attendance_sessionsData, {
      transaction,
    });
  }

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

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

    if (!attendance_sessions) {
      return null;
    }

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

    if (data.session_date !== undefined)
      updatePayload.session_date = data.session_date;
    if (data.session_type !== undefined)
      updatePayload.session_type = data.session_type;
    if (data.notes !== undefined) updatePayload.notes = data.notes;

    updatePayload.updatedById = currentUser.id;

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

    if (data.organization !== undefined) {
      const orgId = globalAccess
        ? data.organization
        : currentUser.organizationId;
      await attendance_sessions.setOrganization(orgId ?? undefined, {
        transaction,
      });
    }
    if (data.campus !== undefined) {
      await attendance_sessions.setCampus(data.campus ?? undefined, {
        transaction,
      });
    }
    if (data.class !== undefined) {
      await attendance_sessions.setClass(data.class ?? undefined, {
        transaction,
      });
    }
    if (data.class_subject !== undefined) {
      await attendance_sessions.setClass_subject(
        data.class_subject ?? undefined,
        { transaction },
      );
    }
    if (data.taken_by !== undefined) {
      await attendance_sessions.setTaken_by(data.taken_by ?? undefined, {
        transaction,
      });
    }

    return attendance_sessions;
  }

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

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

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

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

    if (!attendance_sessions) {
      return null;
    }

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

    const [
      attendance_records_attendance_session,
      organization,
      campus,
      class_,
      class_subject,
      taken_by,
    ] = await Promise.all([
      attendance_sessions.getAttendance_records_attendance_session({
        transaction,
      }),
      attendance_sessions.getOrganization({ transaction }),
      attendance_sessions.getCampus({ transaction }),
      attendance_sessions.getClass({ transaction }),
      attendance_sessions.getClass_subject({ transaction }),
      attendance_sessions.getTaken_by({ transaction }),
    ]);
    output.attendance_records_attendance_session =
      attendance_records_attendance_session;
    output.organization = organization;
    output.campus = campus;
    output.class = class_;
    output.class_subject = class_subject;
    output.taken_by = taken_by;

    return output;
  }

  static async findAll(
    filter: AttendanceSessionsFilter,
    globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<{ rows: AttendanceSessions[]; 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.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}%` })),
                  },
                },
              ],
            }
          : {},
      },
      {
        model: db.class_subjects,
        as: 'class_subject',
        where: filter.class_subject
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.class_subject
                      .split('|')
                      .map((t) => Utils.uuid(t)),
                  },
                },
                {
                  status: {
                    [Op.or]: filter.class_subject
                      .split('|')
                      .map((t) => ({ [Op.iLike]: `%${t}%` })),
                  },
                },
              ],
            }
          : {},
      },
      {
        model: db.staff,
        as: 'taken_by',
        where: filter.taken_by
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.taken_by
                      .split('|')
                      .map((t) => Utils.uuid(t)),
                  },
                },
                {
                  employee_number: {
                    [Op.or]: filter.taken_by
                      .split('|')
                      .map((t) => ({ [Op.iLike]: `%${t}%` })),
                  },
                },
              ],
            }
          : {},
      },
    ];

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.notes) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('attendance_sessions', 'notes', filter.notes),
      };
    }
    if (filter.session_dateRange) {
      const [start, end] = filter.session_dateRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, session_date: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          session_date: {
            ...(typeof where.session_date === 'object'
              ? where.session_date
              : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    if (filter.session_type) {
      where = { ...where, session_type: filter.session_type };
    }
    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.attendance_sessions.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.attendance_sessions,
      'session_type',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default Attendance_sessionsDBApi;
