import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';

@Injectable()
export class YoutubeService {
  private url: string | undefined;
  private key: string | undefined;
  constructor(private configService: ConfigService) {
    this.url = this.configService.get('google.youtubeApiBaseUrl');
    this.key = this.configService.get('google.youtubeApiKey');
  }

  async getYoutubeData(url: string) {
    if (!url) {
      console.error('Video ID is null or empty.');
      return null;
    }

    const videoId = this.extractYouTubeVideoId(url);

    try {
      const response = await axios.get(`${this.url}/videos`, {
        params: {
          id: videoId,
          key: this.key,
          part: 'contentDetails', // 영상 길이는 contentDetails 필드에 포함됩니다.
        },
      });

      const items = response.data.items;

      if (items && items.length > 0) {
        const contentDetails = items[0].contentDetails;
        const durationIso = contentDetails.duration; // PT1H2M3S와 같은 ISO 8601 형식

        // ISO 8601 duration을 초 단위로 변환하는 함수 호출
        const durationSeconds = this.convertIsoDurationToSeconds(durationIso);
        return durationSeconds;
      } else {
        console.warn(`No video found for ID: ${videoId}`);
        return null;
      }
    } catch (error) {
      if (axios.isAxiosError(error)) {
        console.error(
          'Error fetching YouTube video duration:',
          error.response?.data || error.message,
        );
      } else {
        console.error('An unexpected error occurred:', error);
      }
      return null;
    }
  }

  private extractYouTubeVideoId(url: string) {
    const regex =
      /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|shorts\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/;
    const match = url.match(regex);
    return match ? match[1] : null;
  }

  private convertIsoDurationToSeconds(isoDuration: string): number {
    const regex = /P(?:(\d+)D)?T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/;
    const matches = isoDuration.match(regex);

    if (!matches) {
      return 0;
    }

    const days = parseInt(matches[1] || '0', 10);
    const hours = parseInt(matches[2] || '0', 10);
    const minutes = parseInt(matches[3] || '0', 10);
    const seconds = parseInt(matches[4] || '0', 10);

    return days * 24 * 3600 + hours * 3600 + minutes * 60 + seconds;
  }
}
