import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';

export interface PrePlantingConfig {
  isActive: boolean;
  activatedAt: Date | null;
  agreementText?: string | null;
}

@Injectable()
export class PrePlantingAdminClient {
  private readonly logger = new Logger(PrePlantingAdminClient.name);
  private readonly baseUrl: string;

  constructor(
    private readonly configService: ConfigService,
    private readonly httpService: HttpService,
  ) {
    this.baseUrl =
      this.configService.get<string>('ADMIN_SERVICE_URL') ||
      'http://localhost:3010';
  }

  async getPrePlantingConfig(): Promise<PrePlantingConfig> {
    try {
      const response = await firstValueFrom(
        this.httpService.get<PrePlantingConfig>(
          `${this.baseUrl}/api/v1/admin/pre-planting/config`,
        ),
      );
      return response.data;
    } catch (error) {
      this.logger.error('Failed to get pre-planting config', error);
      if (this.configService.get('NODE_ENV') === 'development') {
        this.logger.warn('Development mode: returning default config (active)');
        return { isActive: true, activatedAt: null };
      }
      throw error;
    }
  }
}
