/**
 * Demo seed: 把 N 个 SUPPLY_PO_CREATED 机器人推到 DELIVERY_DELIVERED + 创建配套销售/交付/收款数据
 *
 * 用途：报表页有数据展示（销售/财务汇总）
 *
 * 运行：
 *   cd backend
 *   npx ts-node --transpile-only -r tsconfig-paths/register scripts/seed/seed-delivered-demo.ts [count]
 *
 * 默认 count=8。跳过 lifecycle-guards（直接 snapshot+event 注入）。
 */

import {
  PrismaClient,
  RobotLifecycleStage,
  RobotLifecycleEventType,
  SalesContractStatus,
  SalesOrderStatus,
  DeliveryRequestType,
  DeliveryRequestStatus,
  DeliveryFormStatus,
  RevenueRecognitionStatus,
  PaymentDirection,
  PaymentStatus,
  PaymentMethod,
  PaymentRelatedType,
  SalesLineType,
} from '@prisma/client';

const NIL_ORG = '00000000-0000-0000-0000-000000000000';

async function main() {
  const prisma = new PrismaClient();
  const count = parseInt(process.argv[2] ?? '8', 10);
  console.log(`[seed-delivered-demo] target count: ${count}`);

  // 用 itadmin 作为 createdBy
  const itadmin = await prisma.user.findFirst({ where: { username: 'itadmin' } });
  if (!itadmin) {
    console.error('itadmin user not found, run npm run init:itadmin first');
    process.exit(1);
  }
  const userId = itadmin.id;

  // 选第一个 customer
  const customers = await prisma.customer.findMany({ where: { deletedAt: null } });
  if (customers.length === 0) {
    console.error('no customers found, run db:seed first');
    process.exit(1);
  }
  console.log(`[seed-delivered-demo] using ${customers.length} customers (round-robin)`);

  // 取前 N 个 SUPPLY_PO_CREATED 的 robot
  const robots = await prisma.robotUnit.findMany({
    where: {
      deletedAt: null,
      snapshot: { currentStage: RobotLifecycleStage.SUPPLY_PO_CREATED },
    },
    include: { snapshot: true, purchaseOrderLine: true },
    take: count,
  });
  console.log(`[seed-delivered-demo] found ${robots.length} candidate robots`);
  if (robots.length === 0) {
    console.log('no robots to seed; exit');
    return;
  }

  let success = 0;
  for (let i = 0; i < robots.length; i++) {
    const robot = robots[i];
    const customer = customers[i % customers.length];
    // 销售价 = 采购价 * 1.4 (40% margin), 成本 = 采购价 + 2000 (运输 + 改装)
    const purchasePrice = Number(robot.purchaseOrderLine?.unitPrice ?? 22000);
    const salesPrice = Math.round(purchasePrice * 1.4);
    const cost = purchasePrice + 2000;
    const margin = salesPrice - cost;
    const deliveredAt = new Date(Date.now() - (count - i) * 86400000 * 3); // 错开日期，每 3 天一台

    try {
      await prisma.$transaction(async (tx) => {
        // 1. 创建 SalesOrder
        const so = await tx.salesOrder.create({
          data: {
            soNo: `SO-DEMO-${Date.now()}-${i}`,
            customerId: customer.id,
            currencyCode: robot.purchaseOrderLine?.currencyCode ?? 'USD',
            totalAmount: salesPrice,
            contractStatus: SalesContractStatus.SIGNED,
            status: SalesOrderStatus.COMPLETED,
            signedAt: new Date(deliveredAt.getTime() - 14 * 86400000),
            closedAt: deliveredAt,
            organizationId: robot.organizationId,
            createdById: userId,
          },
        });

        // 2. SalesOrderLine 关联 robot
        await tx.salesOrderLine.create({
          data: {
            salesOrderId: so.id,
            lineNo: 1,
            lineType: SalesLineType.HARDWARE,
            robotUnitId: robot.id,
            unitPrice: salesPrice,
            netAmount: salesPrice,
            currencyCode: so.currencyCode,
          },
        });

        // 3. DeliveryRequest
        const dr = await tx.deliveryRequest.create({
          data: {
            deliveryNo: `DR-DEMO-${Date.now()}-${i}`,
            salesOrderId: so.id,
            customerId: customer.id,
            requestType: DeliveryRequestType.WHITE_GLOVE,
            expectedDate: deliveredAt,
            status: DeliveryRequestStatus.COMPLETED,
            organizationId: robot.organizationId,
            createdById: userId,
          },
        });

        // 4. DeliveryFulfillment（含 cost/grossMargin —— 财务报表用）
        await tx.deliveryFulfillment.create({
          data: {
            deliveryRequestId: dr.id,
            robotUnitId: robot.id,
            deliveredAt,
            signedAt: deliveredAt,
            signedFormStatus: DeliveryFormStatus.SIGNED,
            acceptanceFormStatus: DeliveryFormStatus.SIGNED,
            cost,
            grossMargin: margin,
            revenueRecognition: RevenueRecognitionStatus.RECOGNIZED,
            organizationId: robot.organizationId,
            createdById: userId,
          },
        });

        // 5. INBOUND PaymentRecord（已付款，营收报表用）
        await tx.paymentRecord.create({
          data: {
            paymentNo: `PAY-DEMO-${Date.now()}-${i}`,
            relatedType: PaymentRelatedType.SALES_ORDER,
            relatedId: so.id,
            robotUnitId: robot.id,
            direction: PaymentDirection.INBOUND,
            paymentMethod: PaymentMethod.WIRE_TRANSFER,
            paymentStatus: PaymentStatus.PAID,
            amount: salesPrice,
            currencyCode: so.currencyCode,
            paidAt: new Date(deliveredAt.getTime() - 7 * 86400000),
            organizationId: robot.organizationId,
            createdById: userId,
          },
        });

        // 6. 推进 snapshot.currentStage = DELIVERY_DELIVERED + 加 stage_changed event
        await tx.robotLifecycleEvent.create({
          data: {
            robotUnitId: robot.id,
            eventType: RobotLifecycleEventType.stage_changed,
            fromStage: RobotLifecycleStage.SUPPLY_PO_CREATED,
            toStage: RobotLifecycleStage.DELIVERY_DELIVERED,
            actorUserId: userId,
            occurredAt: deliveredAt,
            organizationId: robot.organizationId,
            createdById: userId,
            payload: { demoSeed: true, jumpStages: 'SUPPLY_PO_CREATED→DELIVERY_DELIVERED' } as any,
          },
        });

        await tx.robotUnitSnapshot.update({
          where: { robotUnitId: robot.id },
          data: {
            currentStage: RobotLifecycleStage.DELIVERY_DELIVERED,
            currentCustomerId: customer.id,
            currentSalesOrderId: so.id,
            currentDeliveryRequestId: dr.id,
            version: { increment: 1 },
            derivedAt: new Date(),
          },
        });
      });

      success++;
      console.log(`  [${i + 1}/${robots.length}] ${robot.ffsn} → DELIVERED · ${customer.name} · $${salesPrice}`);
    } catch (e: any) {
      console.error(`  [${i + 1}/${robots.length}] ${robot.ffsn} failed:`, e?.message ?? e);
    }
  }

  console.log(`\n[seed-delivered-demo] done: ${success}/${robots.length} delivered`);
  await prisma.$disconnect();
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});
