import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiRequestService } from 'src/app/services/api/api-request.service';
import { DynamicField } from './chart-config-manager.component';

@Injectable({
  providedIn: 'root'
})
export class DynamicFieldService {
  private dynamicFieldsUrl = 'api/dynamic-fields';

  constructor(private apiRequest: ApiRequestService) { }

  // Get all dynamic fields for a chart type
  getDynamicFieldsByChartType(chartTypeId: number): Observable<DynamicField[]> {
    const url = `${this.dynamicFieldsUrl}/chart-type/${chartTypeId}`;
    return this.apiRequest.get(url);
  }

  // Get dynamic field by ID
  getDynamicFieldById(id: number): Observable<DynamicField> {
    const url = `${this.dynamicFieldsUrl}/${id}`;
    return this.apiRequest.get(url);
  }

  // Create new dynamic field with optional chart type ID as parameter
  createDynamicField(dynamicField: Partial<DynamicField>, chartTypeId?: number): Observable<DynamicField> {
    let url = this.dynamicFieldsUrl;
    if (chartTypeId) {
      url = `${this.dynamicFieldsUrl}?chartTypeId=${chartTypeId}`;
    }
    return this.apiRequest.post(url, dynamicField);
  }

  // Update dynamic field
  updateDynamicField(id: number, dynamicField: DynamicField): Observable<DynamicField> {
    const url = `${this.dynamicFieldsUrl}/${id}`;
    return this.apiRequest.put(url, dynamicField);
  }

  // Delete dynamic field
  deleteDynamicField(id: number): Observable<void> {
    const url = `${this.dynamicFieldsUrl}/${id}`;
    return this.apiRequest.delete(url);
  }
}