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

type AcademicYearsData = Partial<InferCreationAttributes<AcademicYears>> & {
  organization?: string | null;
};

interface AcademicYearsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  name?: string;
  calendarStart?: string;
  calendarEnd?: string;
  start_dateRange?: Array<string | null | undefined>;
  end_dateRange?: Array<string | null | undefined>;
  active?: boolean | string;
  current?: boolean | string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class Academic_yearsDBApi {
  static async create(
    data: AcademicYearsData,
    options?: DbApiOptions,
  ): Promise<AcademicYears> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const academic_years = await db.academic_years.create(
      {
        id: data.id || undefined,
        name: data.name || null,
        start_date: data.start_date || null,
        end_date: data.end_date || null,
        current: data.current || false,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await academic_years.setOrganization(
      currentUser.organizationId ?? undefined,
      { transaction },
    );

    return academic_years;
  }

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

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

    return db.academic_years.bulkCreate(academic_yearsData, { transaction });
  }

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

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

    if (!academic_years) {
      return null;
    }

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

    if (data.name !== undefined) updatePayload.name = data.name;
    if (data.start_date !== undefined)
      updatePayload.start_date = data.start_date;
    if (data.end_date !== undefined) updatePayload.end_date = data.end_date;
    if (data.current !== undefined) updatePayload.current = data.current;

    updatePayload.updatedById = currentUser.id;

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

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

    return academic_years;
  }

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

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

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

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

    if (!academic_years) {
      return null;
    }

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

    const [
      classes_academic_year,
      timetables_academic_year,
      organization,
    ] = await Promise.all([
      academic_years.getClasses_academic_year({ transaction }),
      academic_years.getTimetables_academic_year({ transaction }),
      academic_years.getOrganization({ transaction }),
    ]);
    output.classes_academic_year = classes_academic_year;
    output.timetables_academic_year = timetables_academic_year;
    output.organization = organization;

    return output;
  }

  static async findAll(
    filter: AcademicYearsFilter,
    globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<{ rows: AcademicYears[]; 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('academic_years', 'name', filter.name),
      };
    }
    if (filter.calendarStart && filter.calendarEnd) {
      where = {
        ...where,
        [Op.or]: [
          {
            start_date: {
              [Op.between]: [filter.calendarStart, filter.calendarEnd],
            },
          },
          {
            end_date: {
              [Op.between]: [filter.calendarStart, filter.calendarEnd],
            },
          },
        ],
      };
    }
    if (filter.start_dateRange) {
      const [start, end] = filter.start_dateRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, start_date: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          start_date: {
            ...(typeof where.start_date === 'object' ? where.start_date : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.end_dateRange) {
      const [start, end] = filter.end_dateRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, end_date: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          end_date: {
            ...(typeof where.end_date === 'object' ? where.end_date : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    if (filter.current) {
      where = { ...where, current: filter.current };
    }
    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.academic_years.findAndCountAll({
      where,
      include: [{ model: db.organizations, as: 'organization' }],
      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.academic_years,
      'name',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default Academic_yearsDBApi;
