import type {
  DesktopMetadataDto,
  MemoryScope,
} from '@/lib/types/desktop'

export type DraftForm = {
  title: string
  summary: string
  memory_type: string
  scope: MemoryScope
  source_ref: string
  project_id: string
  user_id: string
  sensitivity: string
  actor: string
  reason: string
  evidence_refs: string
  // Structured retrieval signals (comma-separated in the form)
  entities: string
  tags: string
  triggers: string
  related_files: string
  related_records: string
  supersedes: string
  applies_to: string
  valid_until: string
}

export const emptyDraft: DraftForm = {
  title: '',
  summary: '',
  memory_type: 'preference',
  scope: 'project',
  source_ref: 'manual:desktop',
  project_id: '',
  user_id: '',
  sensitivity: '',
  actor: '',
  reason: '',
  evidence_refs: '',
  entities: '',
  tags: '',
  triggers: '',
  related_files: '',
  related_records: '',
  supersedes: '',
  applies_to: '',
  valid_until: '',
}

export function buildMetadataDto(form: DraftForm): DesktopMetadataDto {
  return {
    actor: form.actor.trim() || null,
    reason: form.reason.trim() || null,
    evidence_refs: form.evidence_refs
      .split(/[\n,]/)
      .map((s) => s.trim())
      .filter(Boolean),
  }
}

export function buildMetadataFromFields(
  actor: string,
  reason: string,
  evidenceRefsRaw: string
): DesktopMetadataDto {
  return {
    actor: actor.trim() || null,
    reason: reason.trim() || null,
    evidence_refs: evidenceRefsRaw
      .split(/[\n,]/)
      .map((s) => s.trim())
      .filter(Boolean),
  }
}

/** Parse a comma/newline-separated string into a string array, filtering empty entries. */
export function parseCsvField(value: string): string[] {
  return value
    .split(/[\n,]/)
    .map((s) => s.trim())
    .filter(Boolean)
}
