import { Injectable, BadGatewayException } from '@nestjs/common';
import { Logger } from 'pino-nestjs';

const AI_REQUEST_TIMEOUT_MS = 30_000;

export type AiScraperInfo = {
  scraper_name: string;
  display_name: string;
  is_enabled: boolean;
  timezone: string;
  run_hour: number;
  run_minute: number;
  next_run_at: string | null;
  last_started_at: string | null;
  last_scraped_at: string | null;
  last_status: string | null;
  last_message: string | null;
  updated_at: string | null;
};

// All dashboard-triggered scraper interactions go through here so the AI
// service can later be locked down to internal-only access.
@Injectable()
export class AiScraperClient {
  private readonly baseUrl = String(process.env.AI_SERVICE_URL || 'https://ai.thefurfinder.com')
    .trim()
    .replace(/\/+$/, '');

  constructor(private readonly logger: Logger) {}

  private async request(path: string, init?: RequestInit): Promise<any> {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), AI_REQUEST_TIMEOUT_MS);
    try {
      const response = await fetch(`${this.baseUrl}${path}`, {
        ...init,
        headers: { 'Content-Type': 'application/json', ...(init?.headers || {}) },
        signal: controller.signal,
      });

      const body = await response.json().catch(() => null);
      if (!response.ok) {
        this.logger.warn(`AI service ${path} responded ${response.status}`, body);
        throw new BadGatewayException(
          body?.detail || body?.message || `AI service responded with ${response.status}`,
        );
      }
      return body;
    } catch (error: any) {
      if (error instanceof BadGatewayException) throw error;
      this.logger.error(`AI service ${path} request failed`, error);
      throw new BadGatewayException('AI service is unreachable');
    } finally {
      clearTimeout(timeout);
    }
  }

  async listScrapers(): Promise<AiScraperInfo[]> {
    const body = await this.request('/scrapers');
    return Array.isArray(body) ? body : [];
  }

  async runScraper(scraperName: string): Promise<any> {
    return this.request(`/scrapers/${encodeURIComponent(scraperName)}/run`, { method: 'POST' });
  }

  async runAllScrapers(): Promise<any> {
    return this.request('/scrapers/run-all', { method: 'POST' });
  }
}
