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

type TimetablePeriodsData = Partial<
  InferCreationAttributes<TimetablePeriods>
> & {
  organization?: string | null;
  timetable?: string | null;
  class_subject?: string | null;
};

interface TimetablePeriodsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  room?: string;
  starts_atRange?: Array<string | null | undefined>;
  ends_atRange?: Array<string | null | undefined>;
  active?: boolean | string;
  day_of_week?: string;
  timetable?: string;
  class_subject?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class Timetable_periodsDBApi {
  static async create(
    data: TimetablePeriodsData,
    options?: DbApiOptions,
  ): Promise<TimetablePeriods> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const timetable_periods = await db.timetable_periods.create(
      {
        id: data.id || undefined,
        day_of_week: data.day_of_week || null,
        starts_at: data.starts_at || null,
        ends_at: data.ends_at || null,
        room: data.room || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await timetable_periods.setOrganization(
      currentUser.organizationId ?? undefined,
      { transaction },
    );
    await timetable_periods.setTimetable(data.timetable ?? undefined, {
      transaction,
    });
    await timetable_periods.setClass_subject(data.class_subject ?? undefined, {
      transaction,
    });

    return timetable_periods;
  }

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

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

    return db.timetable_periods.bulkCreate(timetable_periodsData, {
      transaction,
    });
  }

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

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

    if (!timetable_periods) {
      return null;
    }

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

    if (data.day_of_week !== undefined)
      updatePayload.day_of_week = data.day_of_week;
    if (data.starts_at !== undefined) updatePayload.starts_at = data.starts_at;
    if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at;
    if (data.room !== undefined) updatePayload.room = data.room;

    updatePayload.updatedById = currentUser.id;

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

    if (data.organization !== undefined) {
      const orgId = globalAccess
        ? data.organization
        : currentUser.organizationId;
      await timetable_periods.setOrganization(orgId ?? undefined, {
        transaction,
      });
    }
    if (data.timetable !== undefined) {
      await timetable_periods.setTimetable(data.timetable ?? undefined, {
        transaction,
      });
    }
    if (data.class_subject !== undefined) {
      await timetable_periods.setClass_subject(data.class_subject ?? undefined, {
        transaction,
      });
    }

    return timetable_periods;
  }

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

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

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

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

    if (!timetable_periods) {
      return null;
    }

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

    const [organization, timetable, class_subject] = await Promise.all([
      timetable_periods.getOrganization({ transaction }),
      timetable_periods.getTimetable({ transaction }),
      timetable_periods.getClass_subject({ transaction }),
    ]);
    output.organization = organization;
    output.timetable = timetable;
    output.class_subject = class_subject;

    return output;
  }

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

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

export default Timetable_periodsDBApi;
