/**
 * Draft templates API — Phase 6 post-resolve templatization flow.
 *
 * A draft is produced when the engineer picks "Run now, templatize after
 * resolve" on the three-option dialog. After Resolve, the TemplatizePrompt
 * modal lists pending drafts and lets the engineer accept (→ real
 * script_templates row) or reject.
 *
 * Mirrors backend endpoints under /api/v1/draft-templates.
 */
import apiClient from './client'

export type DraftStatus = 'pending' | 'accepted' | 'rejected'

export interface DraftTemplate {
  id: string
  account_id: string
  source_session_id: string
  source_user_id: string
  script_body: string
  proposed_parameters: { parameters?: Array<Record<string, unknown>> } | Record<string, unknown>
  proposed_name: string | null
  proposed_category_id: string | null
  status: DraftStatus
  resolved_at: string | null
  promoted_template_id: string | null
  created_at: string
}

export interface DraftAcceptRequest {
  name: string
  category_id: string
  description?: string | null
  parameters_schema: { parameters: Array<Record<string, unknown>> } | Record<string, unknown>
  edited_body?: string | null
}

export interface DraftAcceptResponse {
  draft_id: string
  promoted_template_id: string
  template_slug: string
}

export interface DraftRejectResponse {
  draft_id: string
  status: 'rejected'
}

export const draftTemplatesApi = {
  async list(pendingOnly = true): Promise<DraftTemplate[]> {
    const r = await apiClient.get<{ drafts: DraftTemplate[] }>('/draft-templates', {
      params: { pending_only: pendingOnly },
    })
    return r.data.drafts
  },

  async get(id: string): Promise<DraftTemplate> {
    const r = await apiClient.get<DraftTemplate>(`/draft-templates/${id}`)
    return r.data
  },

  async accept(id: string, data: DraftAcceptRequest): Promise<DraftAcceptResponse> {
    const r = await apiClient.post<DraftAcceptResponse>(
      `/draft-templates/${id}/accept`,
      data,
    )
    return r.data
  },

  async reject(id: string): Promise<DraftRejectResponse> {
    const r = await apiClient.post<DraftRejectResponse>(
      `/draft-templates/${id}/reject`,
    )
    return r.data
  },
}

// ── Account preferences (used by the "don't ask again" opt-out) ────────────

export interface AccountPreferences {
  preferences: Record<string, unknown>
}

export const accountPreferencesApi = {
  async get(): Promise<AccountPreferences> {
    const r = await apiClient.get<AccountPreferences>('/accounts/me/preferences')
    return r.data
  },

  async update(patch: Record<string, unknown>): Promise<AccountPreferences> {
    const r = await apiClient.patch<AccountPreferences>('/accounts/me/preferences', {
      preferences: patch,
    })
    return r.data
  },
}

export default draftTemplatesApi
