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

const router = new Router({ prefix: '/api/notifications' });

// 测试用户ID
const TEST_USER_ID = '1';

/**
 * 获取通知列表
 * GET /api/notifications
 */
router.get('/', optionalAuth, async (ctx) => {
  try {
    const userId = ctx.state.user?.userId || TEST_USER_ID;
    const notifications = await notificationsService.getNotifications(String(userId));

    ctx.body = {
      code: 0,
      message: 'success',
      data: notifications,
    };
  } catch (error: any) {
    ctx.body = {
      code: 400,
      message: error.message || '获取通知失败',
    };
  }
});

/**
 * 标记通知为已读
 * POST /api/notifications/read
 */
router.post('/read', optionalAuth, async (ctx) => {
  try {
    const { id } = ctx.request.body as { id: string };
    await notificationsService.markAsRead(id);

    ctx.body = {
      code: 0,
      message: 'success',
    };
  } catch (error: any) {
    ctx.body = {
      code: 400,
      message: error.message || '标记失败',
    };
  }
});

/**
 * 全部标记为已读
 * PUT /api/notifications/read-all
 */
router.put('/read-all', optionalAuth, async (ctx) => {
  const userId = ctx.state.user?.userId || TEST_USER_ID;
  await prisma.notification.updateMany({
    where: { userId: parseInt(String(userId)), isRead: false },
    data: { isRead: true },
  });
  ctx.body = { code: 0, message: 'success' };
});

export default router;
