/**
 * Hook fuer Template-Rule-Editor: laedt Regeln/Versions/History und exponiert
 * Lifecycle-Actions (submit/approve/publish/reject) + Tenant-Override-CRUD.
 *
 * Alle API-Calls gehen ueber /api/sdk/v1/compliance/* (Next.js-Proxy zum
 * backend-compliance).
 */

import { useCallback } from 'react'
import type {
  ApprovalHistoryEntry,
  Classification,
  Rule,
  RuleCondition,
  RuleVersion,
  TenantRuleOverride,
} from '../_types'

const API_BASE = '/api/sdk/v1/compliance'

async function req<T>(url: string, init?: RequestInit): Promise<T> {
  const res = await fetch(url, {
    ...init,
    headers: {
      'Content-Type': 'application/json',
      ...(init?.headers || {}),
    },
  })
  if (!res.ok) {
    const text = await res.text().catch(() => res.statusText)
    throw new Error(`${res.status}: ${text}`)
  }
  if (res.status === 204) return undefined as T
  return res.json() as Promise<T>
}

export function useRuleEditorActions() {
  const listRules = useCallback(
    (documentType?: string) => {
      const q = documentType ? `?document_type=${encodeURIComponent(documentType)}` : ''
      return req<Rule[]>(`${API_BASE}/template-rules${q}`)
    },
    [],
  )

  const getRule = useCallback(
    (ruleId: string) => req<Rule>(`${API_BASE}/template-rules/${ruleId}`),
    [],
  )

  const listVersions = useCallback(
    (ruleId: string) => req<RuleVersion[]>(`${API_BASE}/template-rules/${ruleId}/versions`),
    [],
  )

  const getVersion = useCallback(
    (versionId: string) => req<RuleVersion>(`${API_BASE}/template-rule-versions/${versionId}`),
    [],
  )

  const createDraftVersion = useCallback(
    (
      ruleId: string,
      payload: {
        classification: Classification
        conditions: RuleCondition
        source_citation: string
        rationale?: string | null
        created_by?: string | null
      },
    ) =>
      req<RuleVersion>(`${API_BASE}/template-rules/${ruleId}/versions`, {
        method: 'POST',
        body: JSON.stringify({
          rule_id: ruleId,
          ...payload,
        }),
      }),
    [],
  )

  const updateDraftVersion = useCallback(
    (
      versionId: string,
      patch: {
        classification?: Classification
        conditions?: RuleCondition
        source_citation?: string
        rationale?: string | null
        change_summary?: string | null
      },
    ) =>
      req<RuleVersion>(`${API_BASE}/template-rule-versions/${versionId}`, {
        method: 'PATCH',
        body: JSON.stringify(patch),
      }),
    [],
  )

  const submitForReview = useCallback(
    (
      versionId: string,
      payload: { change_summary: string; submitter?: string; comment?: string },
    ) =>
      req<RuleVersion>(`${API_BASE}/template-rule-versions/${versionId}/submit-review`, {
        method: 'POST',
        body: JSON.stringify(payload),
      }),
    [],
  )

  const approveVersion = useCallback(
    (versionId: string, payload: { approver?: string; comment?: string } = {}) =>
      req<RuleVersion>(`${API_BASE}/template-rule-versions/${versionId}/approve`, {
        method: 'POST',
        body: JSON.stringify(payload),
      }),
    [],
  )

  const publishVersion = useCallback(
    (versionId: string, payload: { approver?: string; comment?: string } = {}) =>
      req<RuleVersion>(`${API_BASE}/template-rule-versions/${versionId}/publish`, {
        method: 'POST',
        body: JSON.stringify(payload),
      }),
    [],
  )

  const rejectVersion = useCallback(
    (
      versionId: string,
      payload: { rejection_reason: string; rejector?: string; comment?: string },
    ) =>
      req<RuleVersion>(`${API_BASE}/template-rule-versions/${versionId}/reject`, {
        method: 'POST',
        body: JSON.stringify(payload),
      }),
    [],
  )

  const getApprovalHistory = useCallback(
    (versionId: string) =>
      req<ApprovalHistoryEntry[]>(
        `${API_BASE}/template-rule-versions/${versionId}/approval-history`,
      ),
    [],
  )

  const listOverrides = useCallback(
    () => req<TenantRuleOverride[]>(`${API_BASE}/tenant-rule-overrides`),
    [],
  )

  const upsertOverride = useCallback(
    (payload: {
      rule_id: string
      override_classification: Classification | null
      reason: string
      created_by?: string
    }) =>
      req<TenantRuleOverride>(`${API_BASE}/tenant-rule-overrides`, {
        method: 'POST',
        body: JSON.stringify(payload),
      }),
    [],
  )

  const deleteOverride = useCallback(
    (overrideId: string) =>
      req<void>(`${API_BASE}/tenant-rule-overrides/${overrideId}`, { method: 'DELETE' }),
    [],
  )

  return {
    listRules, getRule,
    listVersions, getVersion,
    createDraftVersion, updateDraftVersion,
    submitForReview, approveVersion, publishVersion, rejectVersion,
    getApprovalHistory,
    listOverrides, upsertOverride, deleteOverride,
  }
}
