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 {
  isPolicyDocumentCategory,
  nextPolicyDocumentVersion,
  type PolicyDocumentCategory,
} from '@/shared/constants/policy-documents';
import ValidationError from '@/shared/errors/validation';
import { formatPersonName } from '@/shared/constants/users';
import Utils from '@/db/utils';
import type { PolicyDocuments } from '@/db/models/policy_documents';
import type { CurrentUser, DbApiOptions } from '@/db/api/types';

function requireCategory(value: unknown): PolicyDocumentCategory {
  if (!isPolicyDocumentCategory(value)) {
    throw new ValidationError();
  }
  return value;
}

type PolicyDocumentsData = Partial<InferCreationAttributes<PolicyDocuments>> & {
  organization?: string | null;
  campus?: string | null;
};

interface PolicyDocumentsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  title?: string;
  category?: string;
  tag?: string;
  active?: boolean | string;
  organization?: string;
  campus?: string;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

/** Display name of the user who created the entry (shown as the doc author). */
function authorNameOf(currentUser: CurrentUser): string | null {
  const fullName = formatPersonName(
    currentUser.name_prefix,
    currentUser.firstName,
    currentUser.lastName,
  );
  return fullName || currentUser.email || null;
}

class Policy_documentsDBApi {
  static async create(
    data: PolicyDocumentsData,
    options?: DbApiOptions,
  ): Promise<PolicyDocuments> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const record = await db.policy_documents.create(
      {
        id: data.id || undefined,
        title: data.title ?? '',
        body: data.body ?? null,
        category: requireCategory(data.category),
        tag: data.tag ?? null,
        // Author is the creating user's name (set once at creation).
        author: data.author ?? authorNameOf(currentUser),
        steps: data.steps ?? null,
        autism_considerations: data.autism_considerations ?? null,
        version: data.version ?? 1,
        active: data.active ?? true,
        importHash: data.importHash || null,
        organizationId: currentUser.organizationId ?? null,
        campusId: data.campus ?? currentUser.campusId ?? null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    return record;
  }

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

    const rows = data.map((item, index) => ({
      id: item.id || undefined,
      title: item.title ?? '',
      body: item.body ?? null,
      category: requireCategory(item.category),
      tag: item.tag ?? null,
      author: item.author ?? authorNameOf(currentUser),
      steps: item.steps ?? null,
      autism_considerations: item.autism_considerations ?? null,
      version: item.version ?? 1,
      active: item.active ?? true,
      importHash: item.importHash || null,
      organizationId: currentUser.organizationId ?? null,
      campusId: item.campus ?? currentUser.campusId ?? null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * BULK_IMPORT_TIMESTAMP_STEP_MS),
    }));

    return db.policy_documents.bulkCreate(rows, { transaction });
  }

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

    const record = await findOwnedByPk(db.policy_documents, id, options);
    if (!record) {
      return null;
    }

    const updatePayload: Partial<InferAttributes<PolicyDocuments>> = {};
    if (data.title !== undefined) updatePayload.title = data.title;
    if (data.body !== undefined) updatePayload.body = data.body;
    if (data.category !== undefined) updatePayload.category = data.category;
    if (data.tag !== undefined) updatePayload.tag = data.tag;
    if (data.steps !== undefined) updatePayload.steps = data.steps;
    if (data.autism_considerations !== undefined)
      updatePayload.autism_considerations = data.autism_considerations;
    if (data.active !== undefined) updatePayload.active = data.active;
    // `author` is not changed on update — it records the original creator.
    // Editing the content bumps the version, forcing re-acknowledgment.
    const contentChanged =
      data.title !== undefined ||
      data.body !== undefined ||
      data.steps !== undefined ||
      data.autism_considerations !== undefined;
    const next = nextPolicyDocumentVersion(
      record.version ?? 1,
      contentChanged,
      data.version,
    );
    if (next !== (record.version ?? 1)) {
      updatePayload.version = next;
    }
    updatePayload.updatedById = currentUser.id;

    await record.update(updatePayload, { transaction });
    return record;
  }

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

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

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

    const record = await db.policy_documents.findOne({
      where: { ...where, ...tenantWhere(options?.currentUser) },
      transaction,
    });
    if (!record) {
      return null;
    }

    const output: Record<string, unknown> = record.get({ plain: true });
    const [organization, campus] = await Promise.all([
      record.getOrganization({ transaction }),
      record.getCampus({ transaction }),
    ]);
    output.organization = organization;
    output.campus = campus;
    return output;
  }

  static async findAll(
    filter: PolicyDocumentsFilter,
    globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<{ rows: PolicyDocuments[]; 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.title) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('policy_documents', 'title', filter.title),
      };
    }
    if (filter.category) {
      where = { ...where, category: filter.category };
    }
    if (filter.tag) {
      where = { ...where, tag: filter.tag };
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    if (filter.campus) {
      where = { ...where, campusId: Utils.uuid(filter.campus) };
    }
    if (filter.organization) {
      const listItems = filter.organization
        .split('|')
        .map((item) => Utils.uuid(item));
      where = { ...where, organizationId: { [Op.or]: listItems } };
    }

    if (globalAccess) {
      delete where.organizationId;
    }

    const order: [string, string][] =
      filter.field && filter.sort
        ? [[filter.field, filter.sort]]
        : [['createdAt', 'desc']];

    const { rows, count } = await db.policy_documents.findAndCountAll({
      where,
      include: [
        { model: db.organizations, as: 'organization' },
        { model: db.campuses, as: 'campus' },
      ],
      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.policy_documents,
      'title',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default Policy_documentsDBApi;
