import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, timer } from 'rxjs';
import { switchMap, takeWhile } from 'rxjs/operators';
import { AuthService } from './auth';
import { JobResponse } from './job-types';
import { API_BASE_URL } from '../config';

@Injectable({
  providedIn: 'root'
})
export class JobsService {
  private readonly API_URL = API_BASE_URL;

  constructor(
    private http: HttpClient,
    private authService: AuthService
  ) {}

  getJob(jobId: string): Observable<JobResponse> {
    const headers = this.authService.getAuthHeaders();
    return this.http.get<JobResponse>(`${this.API_URL}/jobs/${jobId}`, { headers });
  }

  pollJob(jobId: string, intervalMs = 2000): Observable<JobResponse> {
    return timer(0, intervalMs).pipe(
      switchMap(() => this.getJob(jobId)),
      takeWhile(
        (job) => job.status === 'queued' || job.status === 'running',
        true
      )
    );
  }

  downloadJobFile(jobId: string): Observable<Blob> {
    const headers = this.authService.getAuthHeaders();
    return this.http.get(`${this.API_URL}/jobs/${jobId}/download`, {
      headers,
      responseType: 'blob'
    });
  }
}
