import apiClient from './client'

export interface PendingPhotoResponse {
  id: number
  user_id: number
  user_name: string | null
  user_email: string | null
  filename: string
  original_filename: string
  file_path: string
  file_size: number
  mime_type: string
  status: string
  submitted_at: string
  reviewed_at: string | null
  reviewed_by: number | null
  rejection_reason: string | null
}

export interface PendingPhotosListResponse {
  items: PendingPhotoResponse[]
  total: number
}

export interface ReviewDecision {
  id: number
  decision: 'approve' | 'reject'
  rejection_reason?: string | null
}

export interface ReviewRequest {
  decisions: ReviewDecision[]
}

export interface ReviewResponse {
  approved: number
  rejected: number
  errors: string[]
  warnings?: string[]  // Informational messages (e.g., duplicates)
}

export interface CleanupResponse {
  deleted_files: number
  deleted_records: number
  errors: string[]
  warnings?: string[]  // Informational messages (e.g., files already deleted)
}

export const pendingPhotosApi = {
  listPendingPhotos: async (statusFilter?: string): Promise<PendingPhotosListResponse> => {
    const { data } = await apiClient.get<PendingPhotosListResponse>(
      '/api/v1/pending-photos',
      {
        params: statusFilter ? { status_filter: statusFilter } : undefined,
      }
    )
    return data
  },

  getPendingPhotoImage: (photoId: number): string => {
    return `${apiClient.defaults.baseURL}/api/v1/pending-photos/${photoId}/image`
  },

  getPendingPhotoImageBlob: async (photoId: number): Promise<string> => {
    // Fetch image as blob with authentication
    const response = await apiClient.get(
      `/api/v1/pending-photos/${photoId}/image`,
      {
        responseType: 'blob',
      }
    )
    // Create object URL from blob
    return URL.createObjectURL(response.data)
  },

  reviewPendingPhotos: async (request: ReviewRequest): Promise<ReviewResponse> => {
    const { data } = await apiClient.post<ReviewResponse>(
      '/api/v1/pending-photos/review',
      request
    )
    return data
  },

  cleanupFiles: async (statusFilter?: string): Promise<CleanupResponse> => {
    const { data } = await apiClient.post<CleanupResponse>(
      '/api/v1/pending-photos/cleanup-files',
      {},
      {
        params: statusFilter ? { status_filter: statusFilter } : undefined,
      }
    )
    return data
  },

  cleanupDatabase: async (statusFilter?: string): Promise<CleanupResponse> => {
    const { data } = await apiClient.post<CleanupResponse>(
      '/api/v1/pending-photos/cleanup-database',
      {},
      {
        params: statusFilter ? { status_filter: statusFilter } : undefined,
      }
    )
    return data
  },
}

