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

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

interface SubjectsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  name?: string;
  code?: string;
  description?: string;
  active?: boolean | string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class SubjectsDBApi {
  static async create(
    data: SubjectsData,
    options?: DbApiOptions,
  ): Promise<Subjects> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const subjects = await db.subjects.create(
      {
        id: data.id || undefined,
        name: data.name || null,
        code: data.code || null,
        description: data.description || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

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

    return subjects;
  }

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

    const subjectsData = data.map((item, index) => ({
      id: item.id || undefined,
      name: item.name || null,
      code: item.code || null,
      description: item.description || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * BULK_IMPORT_TIMESTAMP_STEP_MS),
    }));

    return db.subjects.bulkCreate(subjectsData, { transaction });
  }

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

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

    if (!subjects) {
      return null;
    }

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

    if (data.name !== undefined) updatePayload.name = data.name;
    if (data.code !== undefined) updatePayload.code = data.code;
    if (data.description !== undefined)
      updatePayload.description = data.description;

    updatePayload.updatedById = currentUser.id;

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

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

    return subjects;
  }

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

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

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

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

    if (!subjects) {
      return null;
    }

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

    const [class_subjects_subject, organization] = await Promise.all([
      subjects.getClass_subjects_subject({ transaction }),
      subjects.getOrganization({ transaction }),
    ]);
    output.class_subjects_subject = class_subjects_subject;
    output.organization = organization;

    return output;
  }

  static async findAll(
    filter: SubjectsFilter,
    globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<{ rows: Subjects[]; 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('subjects', 'name', filter.name),
      };
    }
    if (filter.code) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('subjects', 'code', filter.code),
      };
    }
    if (filter.description) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('subjects', 'description', filter.description),
      };
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    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.subjects.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.subjects,
      'name',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default SubjectsDBApi;
