import { cmsApi } from './api.js'

/**
 * Detail metadata for one post type (collection), sourced from the public
 * `GET /collections` introspection endpoint. Read-only by design: collection
 * schemas are file-defined in `actuate.config.ts`, so the Post Type editor
 * inspects the live schema and generates config snippets for changes.
 */
export interface PostTypeFieldSummary {
  name: string
  type: string
  required: boolean
  relationTo?: string | string[]
  options?: unknown[]
}

export interface PostTypeDetail {
  slug: string
  singular: string
  plural: string
  description: string | null
  urlPrefix: string
  icon: string | null
  color: string | null
  fields: PostTypeFieldSummary[]
}

interface CollectionDetailRow {
  slug: string
  labels: { singular: string; plural: string }
  type: string
  urlPrefix: string
  description: string | null
  icon: string | null
  color: string | null
  hidden: boolean
  fields: PostTypeFieldSummary[]
}

export async function fetchPostTypeDetail(slug: string): Promise<PostTypeDetail | null> {
  const res = await cmsApi<CollectionDetailRow[]>('/collections')
  if (res.error || !res.data) {
    throw new Error(res.error ?? 'Failed to load collections')
  }
  const row = res.data.find((c) => c.slug === slug)
  if (!row) return null
  return {
    slug: row.slug,
    singular: row.labels?.singular ?? slug,
    plural: row.labels?.plural ?? slug,
    description: row.description ?? null,
    urlPrefix: row.urlPrefix || slug,
    icon: row.icon ?? null,
    color: row.color ?? null,
    fields: Array.isArray(row.fields) ? row.fields : [],
  }
}

/** Friendly display names for cms-core field types (design's type badges). */
export const FIELD_TYPE_LABELS: Record<string, string> = {
  text: 'Short Text',
  richText: 'Rich Text',
  number: 'Number',
  boolean: 'Boolean',
  date: 'Date',
  slug: 'Slug',
  select: 'Select',
  relationship: 'Relation',
  media: 'Media',
  json: 'JSON',
  color: 'Color',
  url: 'URL',
  email: 'Email',
  array: 'List',
  blocks: 'Blocks',
}

export function fieldTypeLabel(type: string): string {
  return FIELD_TYPE_LABELS[type] ?? type
}

/** "clientName" / "client_name" → "Client Name" for display. */
export function humanizeFieldName(name: string): string {
  return name
    .replace(/[_-]+/g, ' ')
    .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
    .replace(/\s+/g, ' ')
    .trim()
    .replace(/\b\w/g, (c) => c.toUpperCase())
}

/** "Client Name" → "clientName" for generated field keys. */
export function fieldKeyFromName(name: string): string {
  const words = name
    .replace(/[^a-zA-Z0-9]+/g, ' ')
    .trim()
    .split(/\s+/)
    .filter(Boolean)
  if (words.length === 0) return ''
  return words
    .map((w, i) => (i === 0 ? w.toLowerCase() : w[0]!.toUpperCase() + w.slice(1).toLowerCase()))
    .join('')
}

export interface FieldSnippetInput {
  key: string
  label: string
  type: string
  required: boolean
  helpText?: string
}

/**
 * Paste-ready field entry for the collection's `fields` map in
 * `actuate.config.ts` — same escape rules as the New Post Type snippet.
 */
export function renderFieldSnippet(input: FieldSnippetInput): string {
  const esc = (s: string) => s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
  const parts = [`type: '${input.type}'`, `label: '${esc(input.label)}'`]
  if (input.required) parts.push('required: true')
  if (input.helpText?.trim()) parts.push(`admin: { description: '${esc(input.helpText.trim())}' }`)
  if (input.type === 'select') {
    parts.push(`options: [{ label: 'Option A', value: 'option-a' }]`)
  }
  if (input.type === 'relationship') {
    parts.push(`relationTo: 'posts'`)
  }
  return `${input.key}: { ${parts.join(', ')} },`
}
