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

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

// TODO: These types should be moved to @/types/api.ts
export interface GdprDataExportResponse {
  exportId: string;
  status: 'PENDING' | 'COMPLETED' | 'FAILED';
  createdAt: string;
  expiresAt?: string;
  downloadUrl?: string;
}

export interface GdprConsentResponse {
  userId: string;
  marketingEmails: boolean;
  dataProcessing: boolean;
  thirdPartySharing: boolean;
  updatedAt: string;
}

export interface UpdateGdprConsentRequest {
  marketingEmails?: boolean;
  dataProcessing?: boolean;
  thirdPartySharing?: boolean;
}

/**
 * Request data export (GDPR right to data portability)
 * POST /api/v1/gdpr/export
 * Generates export job and sends download link via email
 */
export async function requestDataExport(): Promise<GdprDataExportResponse> {
  return post<GdprDataExportResponse>('/api/v1/gdpr/export');
}

/**
 * Download exported data
 * GET /api/v1/gdpr/export/:exportId/download
 * Returns blob (JSON file)
 */
export async function downloadDataExport(exportId: string): Promise<Blob> {
  const response = await fetch(
    `${process.env.NEXT_PUBLIC_API_URL}/api/v1/gdpr/export/${exportId}/download`,
    {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${
          typeof window !== 'undefined' ? localStorage.getItem('access_token') : ''
        }`,
      },
    }
  );

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

  return response.blob();
}

/**
 * Request account deletion (GDPR right to be forgotten)
 * POST /api/v1/gdpr/delete-account
 * Initiates 30-day account deletion process
 */
export async function requestAccountDeletion(): Promise<SuccessResponse> {
  return post<SuccessResponse>('/api/v1/gdpr/delete-account');
}

/**
 * Cancel pending account deletion
 * POST /api/v1/gdpr/cancel-deletion
 */
export async function cancelAccountDeletion(): Promise<SuccessResponse> {
  return post<SuccessResponse>('/api/v1/gdpr/cancel-deletion');
}

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

/**
 * Update consent preferences
 * PATCH /api/v1/gdpr/consent
 */
export async function updateConsentPreferences(
  data: UpdateGdprConsentRequest
): Promise<GdprConsentResponse> {
  return patch<GdprConsentResponse>('/api/v1/gdpr/consent', data);
}
