import { apiRequest } from './api';
import type { AssetWatermarkContext } from './catalog';

export interface QuestionVideoItem {
  id: string;
  questionId?: string;
  title: string;
  description?: string | null;
  thumbnailUrl?: string | null;
  duration?: number | null;
  accessMode?: string;
  freePreviewSeconds?: number;
  playable?: boolean;
}

export interface VideoPlayback {
  item?: QuestionVideoItem;
  playToken?: string;
  playback?: {
    url?: string;
    expiresAt?: string;
    expiresInSec?: number;
    signatureMode?: string;
  };
  watermark?: AssetWatermarkContext;
  access?: Record<string, unknown>;
}

export interface VideoProgressReport {
  item?: {
    id?: string;
    videoId?: string;
    questionId?: string | null;
    status?: 'issued' | 'started' | 'completed' | 'expired' | 'revoked';
    accessMode?: string;
    consumedQuota?: number;
    playback?: {
      startedAt?: string;
      completedAt?: string | null;
      lastEventType?: 'start' | 'heartbeat' | 'complete';
      lastProgressSeconds?: number;
      durationSeconds?: number | null;
      watchedSeconds?: number;
      completionRate?: number | null;
      updatedAt?: string;
    };
    updatedAt?: string;
  };
}

export async function loadQuestionVideos(questionId: string) {
  return apiRequest<{ videos?: QuestionVideoItem[]; total?: number }>('/api/questions/videos', {
    query: { questionId },
  });
}

export async function playVideo(input: { videoId: string; questionId?: string }) {
  return apiRequest<VideoPlayback>('/api/videos/play', {
    method: 'POST',
    body: input,
  });
}

export async function reportVideoProgress(input: {
  playToken: string;
  eventType: 'start' | 'heartbeat' | 'complete';
  progressSeconds?: number;
  watchedSeconds?: number;
  durationSeconds?: number;
}) {
  return apiRequest<VideoProgressReport>('/api/videos/progress', {
    method: 'POST',
    body: input,
  });
}
