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

@Injectable({
  providedIn: 'root'
})
export class FormService {
  private URL: string = environments.baseUrl;

  constructor(private http: HttpClient) {}

  // 🛡️ Encabezados con token
  private getHeaders(): HttpHeaders {
    const token = localStorage.getItem('token') || '';
    return new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    });
  }

  getAllForms(): Observable<any> {
    return this.http.get(`${this.URL}/formularios`, {
      headers: this.getHeaders()
    });
  }

  getFormById(id: number): Observable<any> {
    return this.http.get(`${this.URL}/formulario/${id}`, {

      headers: this.getHeaders()

    });


  }

  // ✅ Crear un nuevo formulario
  createForm(data: any): Observable<any> {
    return this.http.post(`${this.URL}/createForm`, data, {
      headers: this.getHeaders()
    });
  }
// ✅ Actualizar un formulario existente
updateForm(id: number, data: any): Observable<any> {
  return this.http.put(`${this.URL}/updateForm/${id}`, data, {
    headers: this.getHeaders()
  });

}


  // ✅ Publicar un formulario
publishForm(id: number): Observable<any> {
  return this.http.put<any>(`${this.URL}/formularios/${id}/publish`, {}, {
    headers: this.getHeaders()
  });
}

enviarRespuestas(respuestas: any) {
  return this.http.post('/api/respuestas', respuestas,{
      headers: this.getHeaders()
    });
}

  deleteForm(id: number): Observable<any> {
  return this.http.delete(`${this.URL}/forms/${id}`, {
    headers: this.getHeaders()
  });
}
unpublishForm(id: number): Observable<any> {
  return this.http.put<any>(`${this.URL}/formularios/${id}/unpublish`, {}, {
    headers: this.getHeaders()
  });
}
getPublishedForm() {
  return this.http.get<any>(`${this.URL}/formularios/publicado`,{
      headers: this.getHeaders()
    });
  }




}
