import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
  SiretVerificationPort,
  SiretVerificationResult,
} from '@domain/ports/out/siret-verification.port';

@Injectable()
export class PappersSiretAdapter implements SiretVerificationPort {
  private readonly logger = new Logger(PappersSiretAdapter.name);
  private readonly apiKey: string;
  private readonly baseUrl = 'https://api.pappers.fr/v2';

  constructor(private readonly configService: ConfigService) {
    this.apiKey = this.configService.get<string>('PAPPERS_API_KEY', '');
  }

  async verify(siret: string): Promise<SiretVerificationResult> {
    if (!this.apiKey) {
      this.logger.warn('PAPPERS_API_KEY not configured, skipping SIRET verification');
      return { valid: false };
    }

    try {
      const url = `${this.baseUrl}/entreprise?api_token=${this.apiKey}&siret=${siret}`;
      const response = await fetch(url);

      if (!response.ok) {
        if (response.status === 404) {
          return { valid: false };
        }
        this.logger.error(`Pappers API error: ${response.status} ${response.statusText}`);
        return { valid: false };
      }

      const data = await response.json();

      return {
        valid: true,
        companyName: data.nom_entreprise || data.denomination,
        address: data.siege?.adresse_ligne_1
          ? `${data.siege.adresse_ligne_1}, ${data.siege.code_postal} ${data.siege.ville}`
          : undefined,
      };
    } catch (error: any) {
      this.logger.error(`SIRET verification failed: ${error?.message}`, error?.stack);
      return { valid: false };
    }
  }
}
