import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Material } from '../models/material.model';

@Injectable({
  providedIn: 'root'
})
export class MateriaisService {
  private BASE_URL = 'http://localhost:8080/materiais';

  //private jsonHeaders = new HttpHeaders({ 'Content-Type': 'application/json' });

  private readonly httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    }),
    withCredentials: true
  };

  private readonly httpOptionsFormData = {
    withCredentials: true
  };

  constructor(private http: HttpClient) {}

  listarMateriais(): Observable<Material[]> {
    return this.http.get<Material[]>(`${this.BASE_URL}/listar`, this.httpOptions);  
  }


  criarMaterial(formData: FormData): Observable<string> {
    return this.http.post(`${this.BASE_URL}/criar`, formData, {withCredentials: true, responseType: 'text' });
  }

  downloadArquivo(fileName: string): Observable<Blob> {
    return this.http.get(`${this.BASE_URL}/download/${fileName}`, {
      responseType: 'blob'
    });
  }

  buscarPorId(id: number): Observable<Material> {
    return this.http.get<Material>(`${this.BASE_URL}/${id}`, this.httpOptions);
  }

  editarMaterial(id: number, dados: Material, file?: File): Observable<any> {
    const formData: FormData = new FormData();
    const jsonBlob = new Blob([JSON.stringify(dados)], { type: 'application/json' });
    formData.append('dados', jsonBlob);

    if (file) {
      formData.append('file', file);
    }

    return this.http.put(`${this.BASE_URL}/editar/${id}`, formData, {
      withCredentials: true,
      responseType: 'text' as 'json'
    });
  }

  removerMaterial(id: number): Observable<any> {
    return this.http.delete(`${this.BASE_URL}/remover/${id}`, {
      withCredentials: true,
      responseType: 'text' as const
    });
  }
}