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

type TimetablesData = Partial<InferCreationAttributes<Timetables>> & {
  organization?: string | null;
  campus?: string | null;
  academic_year?: string | null;
};

interface TimetablesFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  name?: string;
  calendarStart?: string;
  calendarEnd?: string;
  effective_fromRange?: Array<string | null | undefined>;
  effective_toRange?: Array<string | null | undefined>;
  active?: boolean | string;
  status?: string;
  campus?: string;
  academic_year?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class TimetablesDBApi {
  static async create(
    data: TimetablesData,
    options?: DbApiOptions,
  ): Promise<Timetables> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const timetables = await db.timetables.create(
      {
        id: data.id || undefined,
        name: data.name || null,
        effective_from: data.effective_from || null,
        effective_to: data.effective_to || null,
        status: data.status || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await timetables.setOrganization(currentUser.organizationId ?? undefined, {
      transaction,
    });
    await timetables.setCampus(data.campus ?? undefined, { transaction });
    await timetables.setAcademic_year(data.academic_year ?? undefined, {
      transaction,
    });

    return timetables;
  }

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

    const timetablesData = data.map((item, index) => ({
      id: item.id || undefined,
      name: item.name || null,
      effective_from: item.effective_from || null,
      effective_to: item.effective_to || 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.timetables.bulkCreate(timetablesData, { transaction });
  }

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

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

    if (!timetables) {
      return null;
    }

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

    if (data.name !== undefined) updatePayload.name = data.name;
    if (data.effective_from !== undefined)
      updatePayload.effective_from = data.effective_from;
    if (data.effective_to !== undefined)
      updatePayload.effective_to = data.effective_to;
    if (data.status !== undefined) updatePayload.status = data.status;

    updatePayload.updatedById = currentUser.id;

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

    if (data.organization !== undefined) {
      const orgId = globalAccess
        ? data.organization
        : currentUser.organizationId;
      await timetables.setOrganization(orgId ?? undefined, { transaction });
    }
    if (data.campus !== undefined) {
      await timetables.setCampus(data.campus ?? undefined, { transaction });
    }
    if (data.academic_year !== undefined) {
      await timetables.setAcademic_year(data.academic_year ?? undefined, {
        transaction,
      });
    }

    return timetables;
  }

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

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

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

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

    if (!timetables) {
      return null;
    }

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

    const [timetable_periods_timetable, organization, campus, academic_year] =
      await Promise.all([
        timetables.getTimetable_periods_timetable({ transaction }),
        timetables.getOrganization({ transaction }),
        timetables.getCampus({ transaction }),
        timetables.getAcademic_year({ transaction }),
      ]);
    output.timetable_periods_timetable = timetable_periods_timetable;
    output.organization = organization;
    output.campus = campus;
    output.academic_year = academic_year;

    return output;
  }

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

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.name) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('timetables', 'name', filter.name),
      };
    }
    if (filter.calendarStart && filter.calendarEnd) {
      where = {
        ...where,
        [Op.or]: [
          {
            effective_from: {
              [Op.between]: [filter.calendarStart, filter.calendarEnd],
            },
          },
          {
            effective_to: {
              [Op.between]: [filter.calendarStart, filter.calendarEnd],
            },
          },
        ],
      };
    }
    if (filter.effective_fromRange) {
      const [start, end] = filter.effective_fromRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, effective_from: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          effective_from: {
            ...(typeof where.effective_from === 'object'
              ? where.effective_from
              : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.effective_toRange) {
      const [start, end] = filter.effective_toRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, effective_to: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          effective_to: {
            ...(typeof where.effective_to === 'object'
              ? where.effective_to
              : {}),
            [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.timetables.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.timetables,
      'name',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default TimetablesDBApi;
