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

type AttendanceRecordsData = Partial<
  InferCreationAttributes<AttendanceRecords>
> & {
  organization?: string | null;
  attendance_session?: string | null;
  student?: string | null;
};

interface AttendanceRecordsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  remarks?: string;
  minutes_lateRange?: Array<number | string | null | undefined>;
  active?: boolean | string;
  status?: string;
  attendance_session?: string;
  student?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class Attendance_recordsDBApi {
  static async create(
    data: AttendanceRecordsData,
    options?: DbApiOptions,
  ): Promise<AttendanceRecords> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

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

    await attendance_records.setOrganization(
      currentUser.organizationId ?? undefined,
      { transaction },
    );
    await attendance_records.setAttendance_session(
      data.attendance_session ?? undefined,
      { transaction },
    );

    return attendance_records;
  }

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

    const attendance_recordsData = data.map((item, index) => ({
      id: item.id || undefined,
      status: item.status || null,
      minutes_late: item.minutes_late || null,
      remarks: item.remarks || 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_records.bulkCreate(attendance_recordsData, {
      transaction,
    });
  }

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

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

    if (!attendance_records) {
      return null;
    }

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.organization !== undefined) {
      const orgId = globalAccess
        ? data.organization
        : currentUser.organizationId;
      await attendance_records.setOrganization(orgId ?? undefined, {
        transaction,
      });
    }
    if (data.attendance_session !== undefined) {
      await attendance_records.setAttendance_session(
        data.attendance_session ?? undefined,
        { transaction },
      );
    }

    return attendance_records;
  }

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

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

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

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

    if (!attendance_records) {
      return null;
    }

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

    const [organization, attendance_session] = await Promise.all([
      attendance_records.getOrganization({ transaction }),
      attendance_records.getAttendance_session({ transaction }),
    ]);
    output.organization = organization;
    output.attendance_session = attendance_session;

    return output;
  }

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

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.remarks) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('attendance_records', 'remarks', filter.remarks),
      };
    }
    if (filter.minutes_lateRange) {
      const [start, end] = filter.minutes_lateRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, minutes_late: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          minutes_late: {
            ...(typeof where.minutes_late === 'object'
              ? where.minutes_late
              : {}),
            [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.attendance_records.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_records,
      'status',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default Attendance_recordsDBApi;
