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

const router = new Router();

// 重命名专辑
router.put('/:id/rename', optionalAuth, async (ctx: Context) => {
  const { id } = ctx.params;
  const { title } = ctx.request.body as { title: string };

  const book = await prisma.book.update({
    where: { id: parseInt(id) },
    data: { title },
  });

  ctx.body = { code: 0, message: 'success', data: book };
});

// 重命名章节
router.put('/:bookId/chapters/:chapterId/rename', optionalAuth, async (ctx: Context) => {
  const { chapterId } = ctx.params;
  const { title } = ctx.request.body as { title: string };

  const chapter = await prisma.bookChapter.update({
    where: { id: parseInt(chapterId) },
    data: { title },
  });

  ctx.body = { code: 0, message: 'success', data: chapter };
});

// 移动章节到新位置
router.put('/:bookId/chapters/:chapterId/move', optionalAuth, async (ctx: Context) => {
  const { bookId, chapterId } = ctx.params;
  const { newNumber } = ctx.request.body as { newNumber: number };

  const chapter = await prisma.bookChapter.findUnique({
    where: { id: parseInt(chapterId) },
  });

  if (!chapter) {
    ctx.status = 404;
    ctx.body = { code: 404, message: '章节不存在' };
    return;
  }

  // 调整其他章节的序号
  if (newNumber > chapter.number) {
    await prisma.bookChapter.updateMany({
      where: {
        bookId: parseInt(bookId),
        number: { gt: chapter.number, lte: newNumber },
      },
      data: { number: { decrement: 1 } },
    });
  } else if (newNumber < chapter.number) {
    await prisma.bookChapter.updateMany({
      where: {
        bookId: parseInt(bookId),
        number: { gte: newNumber, lt: chapter.number },
      },
      data: { number: { increment: 1 } },
    });
  }

  const updatedChapter = await prisma.bookChapter.update({
    where: { id: parseInt(chapterId) },
    data: { number: newNumber },
  });

  ctx.body = { code: 0, message: 'success', data: updatedChapter };
});

export default router;
