/**
 * GCI API Client
 * Communicates with the Go backend via Next.js API proxy at /api/sdk/v1/gci/*
 */

import type {
  GCIResult,
  GCIBreakdown,
  GCIHistoryResponse,
  GCIMatrixResponse,
  NIS2Score,
  NIS2Role,
  ISOGapAnalysis,
  WeightProfile,
} from './types'

const BASE_URL = '/api/sdk/v1/gci'

async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
  const res = await fetch(`${BASE_URL}${path}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      'X-Tenant-ID': typeof window !== 'undefined'
        ? (localStorage.getItem('bp-tenant-id') || 'default')
        : 'default',
      ...options?.headers,
    },
  })

  if (!res.ok) {
    const error = await res.json().catch(() => ({ error: res.statusText }))
    throw new Error(error.error || `API Error: ${res.status}`)
  }

  return res.json()
}

/** GCI Score abrufen */
export async function getGCIScore(profile?: string): Promise<GCIResult> {
  const params = profile ? `?profile=${profile}` : ''
  return apiFetch<GCIResult>(`/score${params}`)
}

/** Detailliertes 4-Level Breakdown abrufen */
export async function getGCIBreakdown(profile?: string): Promise<GCIBreakdown> {
  const params = profile ? `?profile=${profile}` : ''
  return apiFetch<GCIBreakdown>(`/score/breakdown${params}`)
}

/** GCI History abrufen */
export async function getGCIHistory(): Promise<GCIHistoryResponse> {
  return apiFetch<GCIHistoryResponse>('/score/history')
}

/** Compliance Matrix abrufen */
export async function getGCIMatrix(): Promise<GCIMatrixResponse> {
  return apiFetch<GCIMatrixResponse>('/matrix')
}

/** Audit Trail abrufen */
export async function getGCIAuditTrail(profile?: string): Promise<{ tenant_id: string; gci_score: number; audit_trail: any[] }> {
  const params = profile ? `?profile=${profile}` : ''
  return apiFetch(`/audit-trail${params}`)
}

/** Gewichtungsprofile abrufen */
export async function getWeightProfiles(): Promise<{ profiles: WeightProfile[] }> {
  return apiFetch<{ profiles: WeightProfile[] }>('/profiles')
}

/** NIS2 Score abrufen */
export async function getNIS2Score(): Promise<NIS2Score> {
  return apiFetch<NIS2Score>('/nis2/score')
}

/** NIS2 Rollen auflisten */
export async function getNIS2Roles(): Promise<{ roles: NIS2Role[]; total: number }> {
  return apiFetch<{ roles: NIS2Role[]; total: number }>('/nis2/roles')
}

/** NIS2 Rolle zuweisen */
export async function assignNIS2Role(roleId: string, userId: string): Promise<any> {
  return apiFetch('/nis2/roles/assign', {
    method: 'POST',
    body: JSON.stringify({ role_id: roleId, user_id: userId }),
  })
}

/** ISO Gap-Analyse abrufen */
export async function getISOGapAnalysis(): Promise<ISOGapAnalysis> {
  return apiFetch<ISOGapAnalysis>('/iso/gap-analysis')
}

/** ISO Mappings abrufen */
export async function getISOMappings(category?: string): Promise<any> {
  const params = category ? `?category=${category}` : ''
  return apiFetch(`/iso/mappings${params}`)
}
