import type { Contact, TrialNewRequestPublications } from "@/lib/api/types.gen";
import type { TrialContactRow, TrialPublicationRow } from "../types";

const URL_PATTERN = /^https?:\/\/.+/i;

export function mapContactsFromApi(contacts?: Contact[]): TrialContactRow[] {
  return (contacts ?? [])
    .filter((contact) => Boolean(contact.contactDbId))
    .map((contact) => ({
      ...contact,
      contactDbId: contact.contactDbId as string,
      name: contact.name ?? contact.contactDbId,
    }));
}

export function mapPublicationsFromApi(publications?: TrialNewRequestPublications[]): TrialPublicationRow[] {
  return (publications ?? []).map((publication) => ({
    publicationPUI: publication.publicationPUI ?? "",
    publicationReference: publication.publicationReference ?? "",
  }));
}

export function normalizeContactsForSave(contacts: TrialContactRow[]): Contact[] {
  const seen = new Set<string>();
  const normalized: Contact[] = [];

  for (const contact of contacts) {
    const contactDbId = String(contact.contactDbId ?? "").trim();
    if (!contactDbId) continue;
    if (seen.has(contactDbId)) {
      throw new Error("同一试验不能重复添加相同联系人");
    }
    seen.add(contactDbId);
    normalized.push({ contactDbId, name: contact.name });
  }

  return normalized;
}

export function normalizePublicationsForSave(publications: TrialPublicationRow[]): TrialNewRequestPublications[] {
  return publications
    .map((publication) => ({
      publicationPUI: String(publication.publicationPUI ?? "").trim() || undefined,
      publicationReference: String(publication.publicationReference ?? "").trim() || undefined,
    }))
    .filter((publication) => publication.publicationPUI || publication.publicationReference)
    .map((publication) => {
      const reference = publication.publicationReference;
      if (reference && reference.includes("://") && !URL_PATTERN.test(reference)) {
        throw new Error(`出版物引用 URL 格式不正确：${reference}`);
      }
      return publication;
    });
}

export function readTrialContacts(payload: Record<string, unknown>): TrialContactRow[] {
  const value = payload.trialContacts;
  if (Array.isArray(value)) return value as TrialContactRow[];
  return mapContactsFromApi(payload.contacts as Contact[] | undefined);
}

export function readTrialPublications(payload: Record<string, unknown>): TrialPublicationRow[] {
  const value = payload.trialPublications;
  if (Array.isArray(value)) return value as TrialPublicationRow[];
  return mapPublicationsFromApi(payload.publications as TrialNewRequestPublications[] | undefined);
}
