/**
 * 视频发布模块 - API 路由控制器
 */

import Router from '@koa/router';
import { authMiddleware } from '../../middleware/auth';
import {
  savePlatformAccount,
  getPlatformAccount,
  getUserPlatformAccounts,
  deletePlatformAccount,
  validateAccount,
  createPublishTask,
  getPublishTasks,
  getPublishTask,
  updatePublishTask,
  publishToDouyin,
  publishToBilibili,
  getVideoProjectForPublish,
} from './publish.service';

const router = new Router();

// 所有路由需要登录（挂载时会加上 /api/publish 前缀）
router.use(authMiddleware);

// 辅助：从 ctx.state.user 提取数字 userId（JWT 里是字符串，转为 number）
function getUserId(ctx: any): number {
  return Number(ctx.state.user?.userId);
}

// ============ 平台账号管理 ============

/**
 * GET /api/publish/accounts
 * 获取用户已绑定的平台账号
 */
router.get('/accounts', async (ctx) => {
  const userId = getUserId(ctx);
  if (!userId) {
    ctx.status = 401;
    ctx.body = { success: false, error: '请先登录' };
    return;
  }

  const accounts = await getUserPlatformAccounts(userId);
  ctx.body = {
    success: true,
    data: accounts.map((a) => ({
      platform: a.platform,
      nickname: a.nickname,
      avatar: a.avatar,
      isValid: a.isValid,
      createdAt: a.createdAt,
    })),
  };
});

/**
 * POST /api/publish/accounts
 * 绑定平台账号（保存登录凭证）
 */
router.post('/accounts', async (ctx) => {
  const userId = getUserId(ctx);
  if (!userId) {
    ctx.status = 401;
    ctx.body = { success: false, error: '请先登录' };
    return;
  }

  const body = ctx.request.body as any;
  const { platform, cookies, headers, nickname, avatar, expireTime } = body;

  if (!platform || !cookies) {
    ctx.status = 400;
    ctx.body = { success: false, error: '缺少必要参数' };
    return;
  }

  if (!['douyin', 'kuaishou', 'bilibili'].includes(platform)) {
    ctx.status = 400;
    ctx.body = { success: false, error: '不支持的平台' };
    return;
  }

  const account = await savePlatformAccount(userId, platform, {
    cookies,
    headers,
    nickname,
    avatar,
    expireTime: expireTime ? new Date(expireTime) : undefined,
  });

  ctx.body = {
    success: true,
    data: {
      platform: account.platform,
      nickname: account.nickname,
      avatar: account.avatar,
      isValid: account.isValid,
    },
  };
});

/**
 * DELETE /api/publish/accounts/:platform
 * 解绑平台账号
 */
router.delete('/accounts/:platform', async (ctx) => {
  const userId = getUserId(ctx);
  if (!userId) {
    ctx.status = 401;
    ctx.body = { success: false, error: '请先登录' };
    return;
  }

  const platform = ctx.params.platform;
  const success = await deletePlatformAccount(userId, platform);

  if (!success) {
    ctx.status = 404;
    ctx.body = { success: false, error: '账号不存在' };
    return;
  }

  ctx.body = { success: true };
});

/**
 * POST /api/publish/accounts/:platform/validate
 * 验证账号凭证是否有效
 */
router.post('/accounts/:platform/validate', async (ctx) => {
  const userId = getUserId(ctx);
  if (!userId) {
    ctx.status = 401;
    ctx.body = { success: false, error: '请先登录' };
    return;
  }

  const platform = ctx.params.platform;
  const result = await validateAccount(userId, platform);

  ctx.body = { success: true, data: result };
});

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

/**
 * GET /api/publish/tasks
 * 获取发布任务列表
 */
router.get('/tasks', async (ctx) => {
  const userId = getUserId(ctx);
  if (!userId) {
    ctx.status = 401;
    ctx.body = { success: false, error: '请先登录' };
    return;
  }

  const { platform, status, page, pageSize } = ctx.query;
  const result = await getPublishTasks(userId, {
    platform: platform as string,
    status: status as string,
    page: page ? Number(page) : 1,
    pageSize: pageSize ? Number(pageSize) : 20,
  });

  ctx.body = {
    success: true,
    data: {
      items: result.items,
      total: result.total,
    },
  };
});

/**
 * GET /api/publish/tasks/:id
 * 获取单个发布任务
 */
router.get('/tasks/:id', async (ctx) => {
  const userId = getUserId(ctx);
  if (!userId) {
    ctx.status = 401;
    ctx.body = { success: false, error: '请先登录' };
    return;
  }

  const id = Number(ctx.params.id);
  const task = await getPublishTask(id);

  if (!task || task.userId !== userId) {
    ctx.status = 404;
    ctx.body = { success: false, error: '任务不存在' };
    return;
  }

  ctx.body = { success: true, data: task };
});

/**
 * POST /api/publish/tasks
 * 创建发布任务并开始发布
 */
router.post('/tasks', async (ctx) => {
  const userId = getUserId(ctx);
  if (!userId) {
    ctx.status = 401;
    ctx.body = { success: false, error: '请先登录' };
    return;
  }

  const body = ctx.request.body as any;
  const { videoProjectId, videoUrl, platform, title, description, tags, coverUrl } = body;

  if (!platform || !title) {
    ctx.status = 400;
    ctx.body = { success: false, error: '缺少必要参数' };
    return;
  }

  // 支持两种方式：1. 使用 videoProjectId  2. 直接使用 videoUrl
  let finalVideoUrl = videoUrl;
  let finalDescription = description || '';
  let finalCoverUrl = coverUrl;

  if (videoProjectId) {
    // 方式1：通过 videoProjectId 获取视频信息
    const projectInfo = await getVideoProjectForPublish(videoProjectId);
    if (!projectInfo) {
      ctx.status = 404;
      ctx.body = { success: false, error: '视频项目不存在或未生成视频' };
      return;
    }
    finalVideoUrl = projectInfo.videoUrl;
    finalDescription = description || projectInfo.description;
    finalCoverUrl = coverUrl || projectInfo.coverUrl;
  } else if (!videoUrl) {
    // 两种方式都没有
    ctx.status = 400;
    ctx.body = { success: false, error: '请提供 videoProjectId 或 videoUrl' };
    return;
  }

  // 创建发布任务
  const task = await createPublishTask(userId, {
    videoProjectId: videoProjectId || 0, // 如果没有 projectId 则用 0
    platform,
    title,
    description: finalDescription,
    tags,
    coverUrl: finalCoverUrl,
  });

  // 更新视频URL
  await updatePublishTask(task.id!, { videoUrl: finalVideoUrl });

  // 根据平台执行发布
  let result: { success: boolean; publishedUrl?: string; error?: string };

  if (platform === 'douyin') {
    result = await publishToDouyin(userId, task.id!);
  } else if (platform === 'bilibili') {
    result = await publishToBilibili(userId, task.id!);
  } else {
    result = { success: false, error: '该平台暂不支持自动发布' };
  }

  ctx.body = {
    success: true,
    data: {
      taskId: task.id,
      ...result,
    },
  };
});

/**
 * POST /api/publish/tasks/:id/publish
 * 重新发布某个任务
 */
router.post('/tasks/:id/publish', async (ctx) => {
  const userId = getUserId(ctx);
  if (!userId) {
    ctx.status = 401;
    ctx.body = { success: false, error: '请先登录' };
    return;
  }

  const taskId = Number(ctx.params.id);
  const task = await getPublishTask(taskId);

  if (!task || task.userId !== userId) {
    ctx.status = 404;
    ctx.body = { success: false, error: '任务不存在' };
    return;
  }

  let result: { success: boolean; publishedUrl?: string; error?: string };

  if (task.platform === 'douyin') {
    result = await publishToDouyin(userId, taskId);
  } else if (task.platform === 'bilibili') {
    result = await publishToBilibili(userId, taskId);
  } else {
    result = { success: false, error: '该平台暂不支持' };
  }

  ctx.body = { success: true, data: result };
});

// ============ 辅助接口 ============

/**
 * GET /api/publish/video/:projectId/preview
 * 获取视频发布预览信息
 */
router.get('/video/:projectId/preview', async (ctx) => {
  const projectId = Number(ctx.params.projectId);
  const projectInfo = await getVideoProjectForPublish(projectId);

  if (!projectInfo) {
    ctx.status = 404;
    ctx.body = { success: false, error: '视频不存在' };
    return;
  }

  ctx.body = { success: true, data: projectInfo };
});

export default router;
