// 数据库清理 helper
const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

async function cleanDatabase() {
  await prisma.order.deleteMany();
  await prisma.role.deleteMany();
  await prisma.apiKey.deleteMany();
  await prisma.systemConfig.deleteMany();
  await prisma.user.deleteMany();
  // 不删除 Admin 表，保留测试管理员账号
}

async function seedExistingUser() {
  const bcrypt = require('bcryptjs');
  const testData = require('./test-data');
  await prisma.user.create({
    data: {
      account: testData.users.existing.account,
      password: bcrypt.hashSync(testData.users.existing.password, 10),
      isCreator: true,
      creatorName: testData.users.existing.account,
      libraryName: 'E2E测试库',
    },
  });
}

async function seedAdmin() {
  const bcrypt = require('bcryptjs');
  const admin = await prisma.admin.findUnique({ where: { account: 'admin' } });
  if (!admin) {
    await prisma.admin.create({
      data: {
        account: 'admin',
        password: bcrypt.hashSync('admin123', 10),
      },
    });
  }
}

async function disconnect() {
  await prisma.$disconnect();
}

module.exports = { cleanDatabase, seedExistingUser, seedAdmin, disconnect, prisma };
