import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';
import { ApiResponse, PaginatedResponse } from '../models/api.model';

export interface Attachment {
  id: number;
  file_name: string;
  mime_type: string;
  file_size: number;
  attachable_type: string;
  attachable_id: number;
  uploaded_by: number | null;
  created_at: string;
  updated_at: string;
}

@Injectable({ providedIn: 'root' })
export class AttachmentService {
  private http = inject(HttpClient);
  private baseUrl = `${environment.apiUrl}/core/attachments`;

  list(page = 1, perPage = 100, filters?: { attachable_type?: string; attachable_id?: number }): Observable<PaginatedResponse<Attachment>> {
    let params = new HttpParams().set('page', page).set('per_page', perPage);
    if (filters?.attachable_type) params = params.set('attachable_type', filters.attachable_type);
    if (filters?.attachable_id) params = params.set('attachable_id', filters.attachable_id);
    return this.http.get<PaginatedResponse<Attachment>>(this.baseUrl, { params });
  }

  upload(file: File, attachableType = 'general', attachableId = 0): Observable<ApiResponse<Attachment>> {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('attachable_type', attachableType);
    formData.append('attachable_id', String(attachableId));
    return this.http.post<ApiResponse<Attachment>>(this.baseUrl, formData);
  }

  download(attachmentId: number): Observable<Blob> {
    return this.http.get(`${this.baseUrl}/${attachmentId}/download`, { responseType: 'blob' });
  }

  delete(id: number): Observable<{ message: string }> {
    return this.http.delete<{ message: string }>(`${this.baseUrl}/${id}`);
  }
}
