import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ApiConfigService } from '../../../core/services/api-config.service';
import {
  Form1099Box, Form1099Summary, Form1099RecipientDetail,
} from '../models/payee1099.model';

@Injectable({ providedIn: 'root' })
export class Form1099ReportApiService {
  private readonly endpoint: string;

  constructor(private http: HttpClient, apiConfig: ApiConfigService) {
    this.endpoint = apiConfig.getApiUrl('form1099-report');
  }

  getBoxes(): Observable<Form1099Box[]> {
    return this.http.get<Form1099Box[]>(`${this.endpoint}/boxes`);
  }

  getSummary(taxYear: number): Observable<Form1099Summary> {
    return this.http.get<Form1099Summary>(`${this.endpoint}/summary`, {
      params: { taxYear: String(taxYear) },
    });
  }

  getRecipient(payeeId: number, taxYear: number): Observable<Form1099RecipientDetail> {
    return this.http.get<Form1099RecipientDetail>(`${this.endpoint}/recipient/${payeeId}`, {
      params: { taxYear: String(taxYear) },
    });
  }

  // Authenticated blob downloads: routed through HttpClient so the auth
  // interceptor attaches the bearer token (a raw window.open would 401).
  downloadCsv(taxYear: number): Observable<Blob> {
    return this.http.get(`${this.endpoint}/export-csv`, {
      params: { taxYear: String(taxYear) },
      responseType: 'blob',
    });
  }

  downloadCopyB(payeeId: number, taxYear: number): Observable<Blob> {
    return this.http.get(`${this.endpoint}/recipient/${payeeId}/copy-b`, {
      params: { taxYear: String(taxYear) },
      responseType: 'blob',
    });
  }
}
