import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/app/environments/environment';

@Injectable({
  providedIn: 'root',
})
export class SuperAdminDetailsService {
constructor(private http: HttpClient) {}

  private apiEnvUrl = environment.apiURL
  saveSuperAdminContactDetailsForm(
    data: any,
    uploadedDocs: any[],
    applicationId: string,
    user: string,
    userMailId: string
  ): Observable<any> {
    const formData = new FormData();
  
    // Append document details
    uploadedDocs.forEach((doc) => {
      formData.append('files', doc.file); // ✔️ actual File object
      formData.append('types', doc.type);
      formData.append('values', doc.value);
      formData.append('organisationId', doc.organisationId);
      formData.append('contactType', 'Superadmin');
      formData.append('emailId', doc.email);
    });
    const contactBlob = new Blob(
    [JSON.stringify(data.spradmContact)], 
    { type: 'application/json' }
  );
  
    // Append scalar fields
    formData.append('applicationId', applicationId);
    formData.append('user', user);
    formData.append('userMailId', userMailId);
  
    // Serialize and append contacts as JSON
    formData.append('spradmContact',contactBlob);
  
    const apiUrl = this.apiEnvUrl + '/dr/administrativeContact/saveSuperadminDataAlongWithDoc';
  
    return this.http.post<any>(apiUrl, formData, {
      observe: 'response',
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        // ✅ DO NOT set Content-Type manually — browser handles it
      })
    });
  }
}
