import {
  AttachmentType,
  type AttachmentType as AttachmentTypeCode,
} from "../../shared/api/enums";
import type { Id } from "../../shared/api/types";
import {
  isDocumentSummary,
  type DocumentSummary,
} from "../documents/documentTypes";

export interface AttachmentListQuery {
  keyword?: string;
  attachmentType?: AttachmentTypeCode;
  fileExtension?: string;
  updatedFrom?: string;
  updatedTo?: string;
  sortBy?: "documentName" | "createdAt" | "updatedAt" | "viewCount" | "downloadCount";
  sortDirection?: "asc" | "desc";
  page?: number;
  pageSize?: number;
}

export interface MountedAttachmentQuery {
  keyword?: string;
  attachmentType?: AttachmentTypeCode;
  updatedFrom?: string;
  updatedTo?: string;
  page?: number;
  pageSize?: number;
}

export interface AttachmentBindingSummary extends DocumentSummary {
  bindingId: Id;
  bindingSortNo: number;
  mountedPlanCount: number;
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return !!value && typeof value === "object" && !Array.isArray(value);
}

export function isAttachmentBindingSummary(
  value: unknown,
): value is AttachmentBindingSummary {
  return (
    isDocumentSummary(value) &&
    isRecord(value) &&
    typeof value.bindingId === "string" &&
    /^[0-9]+$/.test(value.bindingId) &&
    typeof value.bindingSortNo === "number" &&
    Number.isInteger(value.bindingSortNo) &&
    value.bindingSortNo >= 0 &&
    typeof value.mountedPlanCount === "number" &&
    Number.isInteger(value.mountedPlanCount) &&
    value.mountedPlanCount >= 0
  );
}

export function isAttachmentType(value: unknown): value is AttachmentTypeCode {
  return (
    typeof value === "string" &&
    (Object.values(AttachmentType) as string[]).includes(value)
  );
}
