/**
 * 视频发布模块 - API
 */

import { get, post, del } from './request';

// ============ 类型定义 ============

export interface PlatformAccount {
  platform: 'douyin' | 'kuaishou' | 'bilibili';
  nickname: string;
  avatar: string;
  isValid: boolean;
  createdAt: string;
}

export interface PublishTask {
  id: number;
  userId: number;
  videoProjectId: number;
  platform: 'douyin' | 'kuaishou' | 'bilibili';
  title: string;
  description?: string;
  tags?: string[];
  coverUrl?: string;
  videoUrl?: string;
  status: 'pending' | 'uploading' | 'success' | 'failed';
  errorMsg?: string;
  publishedUrl?: string;
  createdAt: string;
}

export interface VideoPreview {
  title: string;
  description: string;
  videoUrl: string;
  coverUrl?: string;
}

// ============ 平台账号 API ============

/**
 * 获取已绑定的平台账号
 */
export async function getPlatformAccounts(): Promise<PlatformAccount[]> {
  return get<PlatformAccount[]>('/publish/accounts');
}

/**
 * 绑定平台账号（保存登录凭证）
 */
export async function bindPlatformAccount(data: {
  platform: 'douyin' | 'kuaishou' | 'bilibili';
  cookies: string;
  headers?: Record<string, string>;
  nickname?: string;
  avatar?: string;
}): Promise<{ platform: string; nickname: string }> {
  return post('/publish/accounts', data);
}

/**
 * 解绑平台账号
 */
export async function unbindPlatformAccount(
  platform: 'douyin' | 'kuaishou' | 'bilibili'
): Promise<void> {
  return del(`/publish/accounts/${platform}`);
}

/**
 * 验证账号是否有效
 */
export async function validatePlatformAccount(
  platform: 'douyin' | 'kuaishou' | 'bilibili'
): Promise<{ valid: boolean; nickname?: string; error?: string }> {
  return post(`/publish/accounts/${platform}/validate`);
}

// ============ 发布任务 API ============

/**
 * 获取发布任务列表
 */
export async function getPublishTasks(options?: {
  platform?: string;
  status?: string;
  page?: number;
  pageSize?: number;
}): Promise<{ items: PublishTask[]; total: number }> {
  return get('/publish/tasks', options as Record<string, unknown>);
}

/**
 * 获取单个发布任务
 */
export async function getPublishTask(id: number): Promise<PublishTask> {
  return get<PublishTask>(`/publish/tasks/${id}`);
}

/**
 * 创建发布任务并立即发布
 */
export async function createAndPublishTask(data: {
  videoProjectId?: number;
  videoUrl?: string;
  platform: 'douyin' | 'kuaishou' | 'bilibili';
  title: string;
  description?: string;
  tags?: string[];
  coverUrl?: string;
}): Promise<{
  taskId: number;
  success: boolean;
  publishedUrl?: string;
  error?: string;
}> {
  return post('/publish/tasks', data);
}

/**
 * 重新发布任务
 */
export async function republishTask(
  taskId: number
): Promise<{ success: boolean; publishedUrl?: string; error?: string }> {
  return post(`/publish/tasks/${taskId}/publish`);
}

// ============ 辅助 API ============

/**
 * 获取视频发布预览信息
 */
export async function getVideoPublishPreview(
  projectId: number
): Promise<VideoPreview> {
  return get<VideoPreview>(`/publish/video/${projectId}/preview`);
}
