import Router from '@koa/router';
import { Context } from 'koa';
import { optionalAuth } from '../../middleware/auth';
import { prisma } from '../../models';

const TEST_USER_ID = '1';
const router = new Router();

// 获取播放列表
router.get('/', optionalAuth, async (ctx: Context) => {
  const userId = ctx.state.user?.userId || TEST_USER_ID;
  const playlists = await prisma.playlist.findMany({
    where: { userId: parseInt(userId) },
    include: { _count: { select: { items: true } } },
    orderBy: { createdAt: 'desc' },
  });
  ctx.body = { code: 0, message: 'success', data: playlists };
});

// 创建播放列表
router.post('/', optionalAuth, async (ctx: Context) => {
  const userId = ctx.state.user?.userId || TEST_USER_ID;
  const { name, description } = ctx.request.body as { name: string; description?: string };
  const playlist = await prisma.playlist.create({
    data: {
      userId: parseInt(userId),
      name,
      description: description || '',
    },
  });
  ctx.body = { code: 0, message: 'success', data: playlist };
});

// 获取单个播放列表详情
router.get('/:id', optionalAuth, async (ctx: Context) => {
  const { id } = ctx.params;
  const playlist = await prisma.playlist.findUnique({
    where: { id: parseInt(id) },
    include: { items: { orderBy: { order: 'asc' }, include: { chapter: true } } },
  });
  ctx.body = { code: 0, message: 'success', data: playlist };
});

// 添加项目到播放列表
router.post('/:id/items', optionalAuth, async (ctx: Context) => {
  const { id } = ctx.params;
  const { chapterId, audioId } = ctx.request.body as { chapterId?: number; audioId?: string };

  const maxOrder = await prisma.playlistItem.aggregate({
    where: { playlistId: parseInt(id) },
    _max: { order: true },
  });
  const nextOrder = (maxOrder._max.order ?? -1) + 1;

  const item = await prisma.playlistItem.create({
    data: {
      playlistId: parseInt(id),
      chapterId,
      audioId,
      order: nextOrder,
    },
  });
  ctx.body = { code: 0, message: 'success', data: item };
});

// 重新排序项目
router.put('/:id/items/reorder', optionalAuth, async (ctx: Context) => {
  const { id } = ctx.params;
  const { items } = ctx.request.body as { items: { id: number; order: number }[] };
  for (const item of items) {
    await prisma.playlistItem.update({
      where: { id: item.id },
      data: { order: item.order },
    });
  }
  ctx.body = { code: 0, message: 'success' };
});

// 删除项目
router.delete('/:id/items/:itemId', optionalAuth, async (ctx: Context) => {
  const { itemId } = ctx.params;
  await prisma.playlistItem.delete({
    where: { id: parseInt(itemId) },
  });
  ctx.body = { code: 0, message: 'success' };
});

export default router;
