import { Component } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { ToastrService } from "ngx-toastr";
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-env-vars',
  templateUrl: './env-vars.component.html',
  styleUrl: './env-vars.component.css'
})
export class EnvVarsComponent {
  envVars: { name: string; value: string }[] = [];
  displayedColumns: string[] = ['name', 'value'];
  private apiUrl: string;

  constructor(
    private http: HttpClient,
    private toastService: ToastrService,
    private configService: ConfigService
  ) {
    this.apiUrl = `${this.configService.apiUrl}/env-vars`;
  }

  ngOnInit(): void {
    this.loadEnvVars();
  }

  loadEnvVars(): void {
    this.http.get<{ vars: Record<string, string> }>(this.apiUrl).subscribe({
      next: (response) => {
        this.envVars = Object.entries(response.vars).map(([name, value]) => ({ name, value }));
      },
      error: (err) => {
        console.error('Error al cargar las variables de entorno:', err);
        this.toastService.error('No se pudieron cargar las variables de entorno.');
      }
    });
  }

  saveEnvVars(): void {
    const vars = this.envVars.reduce((acc, variable) => {
      acc[variable.name] = variable.value;
      return acc;
    }, {} as Record<string, string>);

    this.http.post(this.apiUrl, { vars }).subscribe({
      next: () => {
        this.toastService.success('Variables de entorno guardadas correctamente.');
      },
      error: (err) => {
        console.error('Error al guardar las variables de entorno:', err);
        this.toastService.error('No se pudieron cargar las variables de entorno.');
      }
    });
  }
}
