import {
  Op,
  type Includeable,
  type InferAttributes,
  type InferCreationAttributes,
  type WhereAttributeHash,
} from 'sequelize';
import db from '@/db/models';
import {
  removeRecord,
  deleteRecordsByIds,
  autocompleteByField,
} 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 FileDBApi from '@/db/api/file';
import type { Documents } from '@/db/models/documents';
import type {
  CurrentUser,
  DbApiOptions,
  FileInput,
} from '@/db/api/types';

type DocumentsData = Partial<InferCreationAttributes<Documents>> & {
  organization?: string | null;
  campus?: string | null;
  file?: FileInput | FileInput[] | null;
};

interface DocumentsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  entity_reference?: string;
  name?: string;
  notes?: string;
  uploaded_atRange?: Array<string | null | undefined>;
  active?: boolean | string;
  entity_type?: string;
  category?: string;
  campus?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

function documentsTableName(): string {
  const name = db.documents.getTableName();
  return typeof name === 'string' ? name : name.tableName;
}

class DocumentsDBApi {
  static async create(
    data: DocumentsData,
    options?: DbApiOptions,
  ): Promise<Documents> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const documents = await db.documents.create(
      {
        id: data.id || undefined,
        entity_type: data.entity_type || null,
        entity_reference: data.entity_reference || null,
        name: data.name || null,
        category: data.category || null,
        uploaded_at: data.uploaded_at || null,
        notes: data.notes || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

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

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: documentsTableName(),
        belongsToColumn: 'file',
        belongsToId: documents.id,
      },
      data.file,
      options,
    );

    return documents;
  }

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

    const documentsData = data.map((item, index) => ({
      id: item.id || undefined,
      entity_type: item.entity_type || null,
      entity_reference: item.entity_reference || null,
      name: item.name || null,
      category: item.category || null,
      uploaded_at: item.uploaded_at || null,
      notes: item.notes || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * BULK_IMPORT_TIMESTAMP_STEP_MS),
    }));

    const documents = await db.documents.bulkCreate(documentsData, {
      transaction,
    });

    for (let i = 0; i < documents.length; i++) {
      await FileDBApi.replaceRelationFiles(
        {
          belongsTo: documentsTableName(),
          belongsToColumn: 'file',
          belongsToId: documents[i].id,
        },
        data[i].file,
        options,
      );
    }

    return documents;
  }

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

    const documents = await db.documents.findByPk(id, { transaction });

    if (!documents) {
      return null;
    }

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

    if (data.entity_type !== undefined)
      updatePayload.entity_type = data.entity_type;
    if (data.entity_reference !== undefined)
      updatePayload.entity_reference = data.entity_reference;
    if (data.name !== undefined) updatePayload.name = data.name;
    if (data.category !== undefined) updatePayload.category = data.category;
    if (data.uploaded_at !== undefined)
      updatePayload.uploaded_at = data.uploaded_at;
    if (data.notes !== undefined) updatePayload.notes = data.notes;

    updatePayload.updatedById = currentUser.id;

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

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

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: documentsTableName(),
        belongsToColumn: 'file',
        belongsToId: documents.id,
      },
      data.file,
      options,
    );

    return documents;
  }

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

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

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

    const documents = await db.documents.findOne({ where, transaction });

    if (!documents) {
      return null;
    }

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

    const [organization, campus, file] = await Promise.all([
      documents.getOrganization({ transaction }),
      documents.getCampus({ transaction }),
      documents.getFile({ transaction }),
    ]);
    output.organization = organization;
    output.campus = campus;
    output.file = file;

    return output;
  }

  static async findAll(
    filter: DocumentsFilter,
    globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<{ rows: Documents[]; 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;
    }

    // The list DTO (`toDocumentDto`) returns only scalar columns, so we don't
    // eager-load organization/file. The campus join is added only when filtering
    // by campus, and selects no columns (filter-only, inner join).
    const include: Includeable[] = [];
    if (filter.campus) {
      include.push({
        model: db.campuses,
        as: 'campus',
        attributes: [],
        required: true,
        where: {
          [Op.or]: [
            {
              id: {
                [Op.in]: filter.campus.split('|').map((t) => Utils.uuid(t)),
              },
            },
            {
              name: {
                [Op.or]: filter.campus
                  .split('|')
                  .map((t) => ({ [Op.iLike]: `%${t}%` })),
              },
            },
          ],
        },
      });
    }

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.entity_reference) {
      where = {
        ...where,
        [Op.and]: Utils.ilike(
          'documents',
          'entity_reference',
          filter.entity_reference,
        ),
      };
    }
    if (filter.name) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('documents', 'name', filter.name),
      };
    }
    if (filter.notes) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('documents', 'notes', filter.notes),
      };
    }
    if (filter.uploaded_atRange) {
      const [start, end] = filter.uploaded_atRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, uploaded_at: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          uploaded_at: {
            ...(typeof where.uploaded_at === 'object' ? where.uploaded_at : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    if (filter.entity_type) {
      where = { ...where, entity_type: filter.entity_type };
    }
    if (filter.category) {
      where = { ...where, category: filter.category };
    }
    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.documents.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.documents,
      'name',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default DocumentsDBApi;
