/**
 * GDPR API
 *
 * Endpoints for GDPR compliance (data export, deletion, consent)
 */

import { get, post, patch } from './client';
import type { SuccessResponse } from '@/types/api';

/**
 * Cookie consent preferences
 */
export interface CookiePreferences {
  essential: boolean;
  functional: boolean;
  analytics: boolean;
  marketing: boolean;
}

/**
 * Response from consent API
 */
export interface ConsentResponse extends CookiePreferences {
  userId: string;
  consentDate: string;
  updatedAt: string;
}

/**
 * Request to update consent
 */
export interface UpdateConsentRequest extends CookiePreferences {
  ipAddress?: string;
  userAgent?: string;
}

/**
 * Data export response
 */
export interface GdprDataExportResponse {
  exportId: string;
  status: 'PENDING' | 'COMPLETED' | 'FAILED';
  createdAt: string;
  expiresAt?: string;
  downloadUrl?: string;
}

/**
 * Request data export (GDPR right to data portability)
 * GET /api/v1/gdpr/export
 * Triggers download of JSON file
 */
export async function requestDataExport(): Promise<Blob> {
  const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/gdpr/export`, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${
        typeof window !== 'undefined' ? localStorage.getItem('accessToken') : ''
      }`,
    },
  });

  if (!response.ok) {
    throw new Error(`Export failed: ${response.statusText}`);
  }

  return response.blob();
}

/**
 * Request data export as CSV
 * GET /api/v1/gdpr/export/csv
 */
export async function requestDataExportCSV(): Promise<Blob> {
  const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/gdpr/export/csv`, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${
        typeof window !== 'undefined' ? localStorage.getItem('accessToken') : ''
      }`,
    },
  });

  if (!response.ok) {
    throw new Error(`Export failed: ${response.statusText}`);
  }

  return response.blob();
}

/**
 * Request account deletion (GDPR right to be forgotten)
 * DELETE /api/v1/gdpr/delete-account
 * Initiates account deletion process
 */
export async function requestAccountDeletion(confirmEmail: string, reason?: string): Promise<void> {
  const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/gdpr/delete-account`, {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${
        typeof window !== 'undefined' ? localStorage.getItem('accessToken') : ''
      }`,
    },
    body: JSON.stringify({ confirmEmail, reason }),
  });

  if (!response.ok) {
    throw new Error(`Deletion failed: ${response.statusText}`);
  }
}

/**
 * Get user consent preferences
 * GET /api/v1/gdpr/consent
 */
export async function getConsentPreferences(): Promise<ConsentResponse | null> {
  return get<ConsentResponse | null>('/api/v1/gdpr/consent');
}

/**
 * Update consent preferences
 * POST /api/v1/gdpr/consent
 */
export async function updateConsentPreferences(
  data: UpdateConsentRequest
): Promise<ConsentResponse> {
  return post<ConsentResponse>('/api/v1/gdpr/consent', data);
}

/**
 * Withdraw specific consent
 * POST /api/v1/gdpr/consent/withdraw
 */
export async function withdrawConsent(
  consentType: 'functional' | 'analytics' | 'marketing'
): Promise<ConsentResponse> {
  return post<ConsentResponse>('/api/v1/gdpr/consent/withdraw', { consentType });
}
