import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { firstValueFrom } from 'rxjs';
import { IAdPlatformAdapter } from '../../common/interfaces/platform-adapter.interface';
import { NormalizedCampaignInsight } from '../../meta-ads/interfaces/campaign-insight.interface';

@Injectable()
export class GoogleAdsService implements IAdPlatformAdapter {
  private readonly logger = new Logger(GoogleAdsService.name);
  readonly platformName = 'google';

  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {}

  async fetchInsights(params: any): Promise<NormalizedCampaignInsight[]> {
    this.logger.log('Fetching insights from Google Ads API (Reporting Service)...');
    return [
      {
        campaignId: 'gg_search_998',
        campaignName: 'Search - SaaS Keywords - MENA',
        impressions: 45200,
        clicks: 2150,
        spend: 645.0,
        ctr: 4.75,
        cpc: 0.30,
        cpm: 14.26,
        dateStart: params.dateStart || '2024-03-01',
        dateStop: params.dateEnd || '2024-03-10',
        source: 'google',
        status: 'ACTIVE',
        platform: 'google',
      },
    ];
  }

  async exchangeCodeForToken(code: string): Promise<string> {
    const clientId = this.configService.get<string>('google.clientId');
    const clientSecret = this.configService.get<string>('google.clientSecret');
    const redirectUri = this.configService.get<string>('google.redirectUri');
    const url = 'https://oauth2.googleapis.com/token';

    try {
      const response = await firstValueFrom(
        this.httpService.post(url, {
          code: code,
          client_id: clientId,
          client_secret: clientSecret,
          redirect_uri: redirectUri,
          grant_type: 'authorization_code',
        })
      );
      return response.data.access_token;
    } catch (error) {
      throw new HttpException('Google Token exchange failed', HttpStatus.BAD_GATEWAY);
    }
  }

  async getAdAccounts(accessToken: string): Promise<any[]> {
    // In a real Google Ads API integration, we would use the CustomerService or 
    // GoogleAdsService.search to list accessible customers.
    return [{ id: 'gg_act_001', name: 'Google Ads Sample Account' }];
  }
}
