import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

/**
 * 联盟返佣种子：创建「阿里云云大使」推广计划，并把技能/工具关联到推广链接。
 * 幂等（upsert），可重复执行。部署时运行：npx ts-node prisma/seed-affiliate.ts
 */
async function main() {
  const program = await prisma.affiliateProgram.upsert({
    where: { slug: 'aliyun-promoter' },
    update: { active: true },
    create: {
      name: '阿里云云大使',
      slug: 'aliyun-promoter',
      provider: '阿里云',
      description: '阿里云推广大使联盟，用户通过推荐链接购买云产品，平台获得返佣。',
      commissionRate: '最高 20%',
      cookieDays: 30,
      homepageUrl: 'https://promotion.aliyun.com/',
      sortOrder: 0,
      active: true,
    },
  });

  const links = [
    {
      title: '阿里云服务器 ECS（新用户特惠）',
      description: '推荐购买阿里云 ECS 云服务器，新用户首购低至 1 折。',
      url: 'https://dashi.aliyun.com/activity/oss?userCode=yzrcloud',
      skillSlug: 'title-craft',
      toolName: '通义千问',
      tags: '云计算,服务器,阿里云',
      estimatedCommission: 15,
      isFeatured: true,
    },
    {
      title: '阿里云 AI 大模型 API（百炼平台）',
      description: '通义千问/百炼大模型 API，按量计费，适合开发者接入。',
      url: 'https://bailian.aliyun.com/?userCode=yzrcloud',
      skillSlug: 'payment-chaser',
      toolName: '通义千问',
      tags: '大模型,API,AI',
      estimatedCommission: 12,
      isFeatured: true,
    },
    {
      title: '阿里云对象存储 OSS',
      description: '推荐企业/开发者使用 OSS 存储，长期稳定低成本。',
      url: 'https://dashi.aliyun.com/activity/oss?userCode=yzrcloud',
      skillSlug: null,
      toolName: 'WPS AI',
      tags: '存储,对象存储',
      estimatedCommission: 8,
      isFeatured: false,
    },
  ];

  for (const link of links) {
    let skillId: string | null = null;
    if (link.skillSlug) {
      const skill = await prisma.skill.findUnique({ where: { id: link.skillSlug } });
      skillId = skill?.id ?? null;
    }
    let toolId: number | null = null;
    if (link.toolName) {
      const tool = await prisma.tool.findFirst({ where: { name: link.toolName } });
      toolId = tool?.id ?? null;
    }

    await prisma.affiliateLink.upsert({
      where: { title: link.title },
      update: { url: link.url, active: true, skillId, toolId },
      create: {
        programId: program.id,
        title: link.title,
        description: link.description,
        url: link.url,
        tags: link.tags,
        estimatedCommission: link.estimatedCommission,
        isFeatured: link.isFeatured,
        skillId,
        toolId,
        active: true,
      },
    });
  }

  const count = await prisma.affiliateLink.count();
  console.log(`✅ 联盟返佣种子完成，当前推广链接 ${count} 条`);
}

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