import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { ApiClientService } from "../../services/api/api-client.service";
import { DataUrlFile } from "../../interfaces/image.interface";

export interface PdfApiResponse {
  data: {
    downloadUrl: string;
  };
}

export interface PdfUploadResponse {
  fileId: number;
  fileName: string;
  fileSize: number;
  fileType: string;
  uploadDate: string;
  downloadUrl?: string;
}

@Injectable({
  providedIn: "root",
})
export class PdfUploadService {
  constructor(private apiClient: ApiClientService) {}

  /**
   * Solicita URL para upload de PDF
   */
  uploadPdfUrl(filename: string): Observable<DataUrlFile> {
    const body = {
      filename: filename,
      acl: "private",
    };
    return this.apiClient.post<DataUrlFile>("file/get-upload-url", body);
  }

  /**
   * Confirma o upload do PDF após envio para S3
   */
  uploadPdfConfirm(fileUrl: string): Observable<PdfUploadResponse> {
    const body = {
      storageKey: fileUrl,
    };
    return this.apiClient.post<PdfUploadResponse>("file/confirm", body);
  }

  /**
   * Obtém URL de download de um PDF por ID
   */
  getPdfById(id: number): Observable<PdfApiResponse> {
    return this.apiClient.get(`file/${id}/download-url`);
  }

  /**
   * Upload direto de arquivo PDF (método alternativo)
   */
  uploadPdfDirect(file: File, entityType?: string, entityId?: string): Observable<PdfUploadResponse> {
    const formData = new FormData();
    formData.append('file', file);
    
    if (entityType) {
      formData.append('entityType', entityType);
    }
    
    if (entityId) {
      formData.append('entityId', entityId);
    }

    return this.apiClient.post<PdfUploadResponse>("file/upload-pdf", formData);
  }

  /**
   * Deleta um PDF por ID
   */
  deletePdf(id: number): Observable<void> {
    return this.apiClient.delete<void>(`file/${id}`);
  }

  /**
   * Obtém metadados de múltiplos PDFs por IDs
   */
  getPdfsByIds(ids: number[]): Observable<PdfUploadResponse[]> {
    const body = { fileIds: ids };
    return this.apiClient.post<PdfUploadResponse[]>("file/batch-info", body);
  }

  /**
   * Atualiza metadados de um PDF (nome, descrição, etc.)
   */
  updatePdfMetadata(id: number, metadata: { fileName?: string; description?: string }): Observable<PdfUploadResponse> {
    return this.apiClient.patch<PdfUploadResponse>(`file/${id}/metadata`, metadata);
  }
}
