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();

// 批量删除历史记录（使用POST避免DELETE body问题）
router.post('/batch-delete', optionalAuth, async (ctx: Context) => {
  const userId = ctx.state.user?.userId || TEST_USER_ID;
  const body = ctx.request.body as {
    ids: string[];
  };

  if (!body || !body.ids || !Array.isArray(body.ids)) {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      message: 'ids 参数必须是数组',
    };
    return;
  }

  try {
    // 删除 AudioRecord 记录
    const result = await prisma.audioRecord.deleteMany({
      where: {
        audioId: { in: body.ids },
      },
    });

    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        deletedCount: result.count,
      },
    };
  } catch (error) {
    console.error('批量删除历史记录失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '删除失败',
    };
  }
});

// 保留DELETE方法作为兼容
router.delete('/batch', optionalAuth, async (ctx: Context) => {
  const userId = ctx.state.user?.userId || TEST_USER_ID;
  const body = ctx.request.body as {
    ids: string[];
  };

  // 尝试从body获取，如果不行从query获取
  let ids: string[] = [];
  if (body && body.ids && Array.isArray(body.ids)) {
    ids = body.ids;
  } else if (ctx.query.ids) {
    try {
      ids = JSON.parse(ctx.query.ids as string);
    } catch {
      // 忽略
    }
  }

  if (!ids || !Array.isArray(ids) || ids.length === 0) {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      message: 'ids 参数必须是数组',
    };
    return;
  }

  try {
    // 删除 AudioRecord 记录
    const result = await prisma.audioRecord.deleteMany({
      where: {
        audioId: { in: ids },
      },
    });

    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        deletedCount: result.count,
      },
    };
  } catch (error) {
    console.error('批量删除历史记录失败:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '删除失败',
    };
  }
});

export default router;
