// 创建测试家长账号脚本
// 运行方式: npx ts-node scripts/create-test-parent.ts

import { PrismaClient } from '@prisma/client';
import * as bcrypt from 'bcrypt';

const prisma = new PrismaClient();

async function main() {
  console.log('开始创建测试家长账号...');

  // 获取第一个租户
  const tenant = await prisma.tenant.findFirst();

  if (!tenant) {
    console.log('未找到租户，请先创建学校');
    return;
  }

  console.log(`使用租户: ${tenant.name} (ID: ${tenant.id})`);

  // 获取一些学生用于关联
  const students = await prisma.student.findMany({
    where: { tenantId: tenant.id },
    take: 5,
  });

  console.log(`找到 ${students.length} 个学生`);

  // 创建测试家长
  const hashedPassword = await bcrypt.hash('123456', 10);

  const parentData = [
    {
      name: '张爸爸',
      phone: '13800138001',
      email: 'zhang@test.com',
      loginAccount: 'parent1',
      passwordHash: hashedPassword,
    },
    {
      name: '李妈妈',
      phone: '13800138002',
      email: 'li@test.com',
      loginAccount: 'parent2',
      passwordHash: hashedPassword,
    },
  ];

  for (const data of parentData) {
    // 检查是否已存在
    const existing = await prisma.parent.findUnique({
      where: { loginAccount: data.loginAccount },
    });

    if (existing) {
      console.log(`家长 ${data.loginAccount} 已存在，跳过`);
      continue;
    }

    const parent = await prisma.parent.create({
      data: {
        tenantId: tenant.id,
        ...data,
        status: 'ACTIVE',
      },
    });

    console.log(`创建家长: ${parent.name} (${parent.loginAccount})`);

    // 关联学生
    if (students.length > 0) {
      const studentToLink = students[parentData.indexOf(data) % students.length];

      await prisma.parentStudent.create({
        data: {
          parentId: parent.id,
          studentId: studentToLink.id,
          relationship: data.name.includes('爸爸') ? 'FATHER' : 'MOTHER',
        },
      });

      console.log(`  -> 关联学生: ${studentToLink.name}`);
    }
  }

  console.log('\n测试家长账号创建完成!');
  console.log('登录账号: parent1 / parent2');
  console.log('密码: 123456');
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
