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 { type } = ctx.query as { type?: string };
  const where: any = { userId: parseInt(userId) };
  if (type) where.type = type;
  const drafts = await prisma.draft.findMany({
    where,
    orderBy: { updatedAt: 'desc' },
  });
  ctx.body = { code: 0, message: 'success', data: drafts };
});

// 获取单个草稿
router.get('/:id', optionalAuth, async (ctx: Context) => {
  const { id } = ctx.params;
  const draft = await prisma.draft.findUnique({
    where: { id: parseInt(id) },
  });
  ctx.body = { code: 0, message: 'success', data: draft };
});

// 保存草稿
router.post('/', optionalAuth, async (ctx: Context) => {
  const userId = ctx.state.user?.userId || TEST_USER_ID;
  const data = ctx.request.body as {
    type: string;
    title?: string;
    content?: string;
    metadata?: string;
  };
  const draft = await prisma.draft.create({
    data: {
      userId: parseInt(userId),
      type: data.type,
      title: data.title,
      content: data.content,
      metadata: data.metadata,
      autoSavedAt: new Date(),
    },
  });
  ctx.body = { code: 0, message: 'success', data: draft };
});

// 更新草稿
router.put('/:id', optionalAuth, async (ctx: Context) => {
  const { id } = ctx.params;
  const data = ctx.request.body as {
    title?: string;
    content?: string;
    metadata?: string;
  };
  const draft = await prisma.draft.update({
    where: { id: parseInt(id) },
    data: { ...data, autoSavedAt: new Date() },
  });
  ctx.body = { code: 0, message: 'success', data: draft };
});

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

export default router;
