import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService, UploadProgress } from '../../../core/services/api.service';
import {
  DocumentResponseDto,
  DocumentVersionResponseDto,
  DownloadUrlResponseDto,
  DocumentType,
} from '../../../api/models';

@Injectable({
  providedIn: 'root',
})
export class DocumentService {
  private readonly api = inject(ApiService);

  getDocuments(requestId: string): Observable<DocumentResponseDto[]> {
    return this.api.get<DocumentResponseDto[]>(`/requests/${requestId}/documents`);
  }

  getDocument(requestId: string, documentId: string): Observable<DocumentResponseDto> {
    return this.api.get<DocumentResponseDto>(`/requests/${requestId}/documents/${documentId}`);
  }

  getDocumentVersions(
    requestId: string,
    documentId: string
  ): Observable<DocumentVersionResponseDto[]> {
    return this.api.get<DocumentVersionResponseDto[]>(
      `/requests/${requestId}/documents/${documentId}/versions`
    );
  }

  uploadDocument(
    requestId: string,
    file: File,
    docType: DocumentType,
    description?: string
  ): Observable<DocumentResponseDto> {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('docType', docType);
    if (description) {
      formData.append('description', description);
    }
    return this.api.upload<DocumentResponseDto>(`/requests/${requestId}/documents`, formData);
  }

  /**
   * Upload document with progress tracking
   */
  uploadDocumentWithProgress(
    requestId: string,
    file: File,
    docType: DocumentType,
    description?: string
  ): Observable<UploadProgress<DocumentResponseDto>> {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('docType', docType);
    if (description) {
      formData.append('description', description);
    }
    return this.api.uploadWithProgress<DocumentResponseDto>(`/requests/${requestId}/documents`, formData);
  }

  updateDocument(
    requestId: string,
    documentId: string,
    file: File
  ): Observable<DocumentResponseDto> {
    const formData = new FormData();
    formData.append('file', file);
    return this.api.upload<DocumentResponseDto>(
      `/requests/${requestId}/documents/${documentId}`,
      formData
    );
  }

  deleteDocument(requestId: string, documentId: string): Observable<void> {
    return this.api.delete<void>(`/requests/${requestId}/documents/${documentId}`);
  }

  getDownloadUrl(requestId: string, documentId: string): Observable<DownloadUrlResponseDto> {
    return this.api.get<DownloadUrlResponseDto>(
      `/requests/${requestId}/documents/${documentId}/download`
    );
  }

  verifyDocument(requestId: string, documentId: string): Observable<{ verified: boolean }> {
    return this.api.get<{ verified: boolean }>(
      `/requests/${requestId}/documents/${documentId}/verify`
    );
  }
}
