/**
 * DSR API CRUD Operations
 *
 * List, create, read, update operations for DSR requests.
 */

import {
  DSRRequest,
  DSRCreateRequest,
  DSRStatistics,
} from './types'
import { BackendDSR, transformBackendDSR, getSdkHeaders } from './api-types'

// =============================================================================
// LIST & STATISTICS
// =============================================================================

/**
 * Fetch DSR list from compliance backend via proxy
 */
export async function fetchSDKDSRList(): Promise<{ requests: DSRRequest[]; statistics: DSRStatistics }> {
  const [listRes, statsRes] = await Promise.all([
    fetch('/api/sdk/v1/compliance/dsr?limit=100', { headers: getSdkHeaders() }),
    fetch('/api/sdk/v1/compliance/dsr/stats', { headers: getSdkHeaders() }),
  ])

  if (!listRes.ok) {
    throw new Error(`HTTP ${listRes.status}`)
  }

  const listData = await listRes.json()
  const backendDSRs: BackendDSR[] = listData.requests || []
  const requests = backendDSRs.map(transformBackendDSR)

  let statistics: DSRStatistics
  if (statsRes.ok) {
    const statsData = await statsRes.json()
    statistics = {
      total: statsData.total || 0,
      byStatus: statsData.by_status || { intake: 0, identity_verification: 0, processing: 0, completed: 0, rejected: 0, cancelled: 0 },
      byType: statsData.by_type || { access: 0, rectification: 0, erasure: 0, restriction: 0, portability: 0, objection: 0 },
      overdue: statsData.overdue || 0,
      dueThisWeek: statsData.due_this_week || 0,
      averageProcessingDays: statsData.average_processing_days || 0,
      completedThisMonth: statsData.completed_this_month || 0,
    }
  } else {
    statistics = {
      total: requests.length,
      byStatus: {
        intake: requests.filter(r => r.status === 'intake').length,
        identity_verification: requests.filter(r => r.status === 'identity_verification').length,
        processing: requests.filter(r => r.status === 'processing').length,
        completed: requests.filter(r => r.status === 'completed').length,
        rejected: requests.filter(r => r.status === 'rejected').length,
        cancelled: requests.filter(r => r.status === 'cancelled').length,
      },
      byType: {
        access: requests.filter(r => r.type === 'access').length,
        rectification: requests.filter(r => r.type === 'rectification').length,
        erasure: requests.filter(r => r.type === 'erasure').length,
        restriction: requests.filter(r => r.type === 'restriction').length,
        portability: requests.filter(r => r.type === 'portability').length,
        objection: requests.filter(r => r.type === 'objection').length,
      },
      overdue: 0,
      dueThisWeek: 0,
      averageProcessingDays: 0,
      completedThisMonth: 0,
    }
  }

  return { requests, statistics }
}

// =============================================================================
// SINGLE RESOURCE OPERATIONS
// =============================================================================

/**
 * Create a new DSR via compliance backend
 */
export async function createSDKDSR(request: DSRCreateRequest): Promise<void> {
  const body = {
    request_type: request.type,
    requester_name: request.requester.name,
    requester_email: request.requester.email,
    requester_phone: request.requester.phone || null,
    requester_address: request.requester.address || null,
    requester_customer_id: request.requester.customerId || null,
    source: request.source,
    source_details: request.sourceDetails || null,
    request_text: request.requestText || '',
    priority: request.priority || 'normal',
  }
  const res = await fetch('/api/sdk/v1/compliance/dsr', {
    method: 'POST',
    headers: getSdkHeaders(),
    body: JSON.stringify(body),
  })
  if (!res.ok) {
    throw new Error(`HTTP ${res.status}`)
  }
}

/**
 * Fetch a single DSR by ID from compliance backend
 */
export async function fetchSDKDSR(id: string): Promise<DSRRequest | null> {
  const res = await fetch(`/api/sdk/v1/compliance/dsr/${id}`, {
    headers: getSdkHeaders(),
  })
  if (!res.ok) {
    return null
  }
  const data = await res.json()
  if (!data || !data.id) return null
  return transformBackendDSR(data)
}

/**
 * Update DSR status via compliance backend
 */
export async function updateSDKDSRStatus(id: string, status: string): Promise<void> {
  const res = await fetch(`/api/sdk/v1/compliance/dsr/${id}/status`, {
    method: 'POST',
    headers: getSdkHeaders(),
    body: JSON.stringify({ status }),
  })
  if (!res.ok) {
    throw new Error(`HTTP ${res.status}`)
  }
}

/**
 * Update DSR fields (priority, notes, etc.)
 */
export async function updateDSR(id: string, data: Record<string, any>): Promise<DSRRequest> {
  const res = await fetch(`/api/sdk/v1/compliance/dsr/${id}`, {
    method: 'PUT',
    headers: getSdkHeaders(),
    body: JSON.stringify(data),
  })
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
  return transformBackendDSR(await res.json())
}
