import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';
import {
  CashboxExportFormat,
  CashboxExportSubscription,
  UpdateCashboxExportSubscription,
} from '../../models/cashbox-export.model';

@Injectable({ providedIn: 'root' })
export class CashboxExportApi {
  private readonly http = inject(HttpClient);
  private readonly baseUrl = `${environment.apiUrl}cashbox-export`;

  exportCashbox(
    teamId: number,
    from: string,
    to: string,
    format: CashboxExportFormat,
  ): Observable<Blob> {
    const params = new HttpParams().set('from', from).set('to', to).set('format', format);
    return this.http.get(`${this.baseUrl}/${teamId}`, { params, responseType: 'blob' });
  }

  getSubscription(teamId: number): Observable<CashboxExportSubscription> {
    return this.http.get<CashboxExportSubscription>(`${this.baseUrl}/${teamId}/subscription`);
  }

  updateSubscription(
    teamId: number,
    dto: UpdateCashboxExportSubscription,
  ): Observable<CashboxExportSubscription> {
    return this.http.put<CashboxExportSubscription>(`${this.baseUrl}/${teamId}/subscription`, dto);
  }

  triggerRunNow(): Observable<void> {
    return this.http.post<void>(`${this.baseUrl}/admin/run`, null);
  }
}
