import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';
import { CreateVideoDto } from 'src/modules/videos/dto/create.video.dto';
import { VideoProvider } from '../interfaces/video-provider.interface';

@Injectable()
export class KlingProvider implements VideoProvider {
  private apiBase = 'https://api.klingai.com/v1/videos/text2video';
  private apiKey: string;

  constructor(private configService: ConfigService) {
    this.apiKey = this.configService.get<string>('KLING_API_KEY')!;
  }

  async createVideo(dto: CreateVideoDto) {
    try {
      const res = await axios.post(
        this.apiBase,
        {
          model_name: dto.model_name || 'kling-v1',
          prompt: dto.prompt,
          negative_prompt: dto.negative_prompt ?? null,
          sound: dto.sound ?? 'off',
          cfg_scale: dto.cfg_scale ?? 0.5,
          mode: dto.mode ?? 'std',
          camera_control: dto.camera_control ?? null,
          aspect_ratio: dto.aspect_ratio ?? '16:9',
          duration: dto.duration ?? '5',
          callback_url: dto.callback_url ?? null,
          external_task_id: dto.external_task_id ?? null,
        },
        {
          headers: {
            Authorization: `Bearer ${this.apiKey}`,
            'Content-Type': 'application/json',
          },
        },
      );

      return res.data;
    } catch (e: any) {
      throw new HttpException(
        e.response?.data || 'Kling create video failed',
        HttpStatus.BAD_GATEWAY,
      );
    }
  }

  async getTask(taskId: string, externalTaskId?: string) {
    const url = externalTaskId
      ? `${this.apiBase}?external_task_id=${externalTaskId}`
      : `${this.apiBase}/${taskId}`;

    const res = await axios.get(url, {
      headers: { Authorization: `Bearer ${this.apiKey}` },
    });

    return res.data;
  }

  async listTasks(page = 1, size = 30) {
    const res = await axios.get(
      `${this.apiBase}?pageNum=${page}&pageSize=${size}`,
      {
        headers: { Authorization: `Bearer ${this.apiKey}` },
      },
    );
    return res.data;
  }
}
