import { Test } from '@nestjs/testing';
import { PlanAssignmentService } from '../src/modules/plan/plan-assignment.service';
import { PrismaService } from '../src/prisma/prisma.service';

/**
 * 批次归因走**账本**(plan_event_logs.assignment_id)。
 *
 * 🔴 起因是一个不报错的真 bug:`followup_plans.assignment_id` **会被下一次分配覆盖**。
 *   一条单退回/到期回池后被后面的批次挑走,旧批次就少一个人 ——
 *   **批次跑得越久(退回重分越多)缩得越厉害**,而且没有任何报错。
 *   实测:c02e1b80 分过 9 条,重分之后 `planned` 显示 **0**。
 *   (与 supersededAt 那个坑同构:批次跑得越有进展,数字反而越小。)
 *
 * 另一半:到期与退回**必须分开数**。主管的下一步动作是相反的 ——
 *   退回多 → 分配策略不对(派给了不该派的人);
 *   到期多 → 派多了 / 时效太紧 / 人不在岗。
 *   合成一个"回池率"两种病都看不出来。
 */

const SCOPE = {
  hostId: 'h1', tenantId: 't1', sourceUnits: [] as string[], clinicIds: [] as string[], userId: 'u1',
} as never;
const BATCH = 'c02e1b80-1111-4222-8333-444455556666';

function makePrisma(opts: {
  /** 现在**还归本批**的 plan(重分走的人不在这里 —— 那正是问题所在) */
  plans?: Array<{ id: string; status: string; assigneeUserId: string | null; releaseReason: string | null }>;
  /** 账本口径的一行汇总;不传 = 模拟老批次(账本没记批次号) */
  ledger?: { planned: number; agents: number; released: number; expired: number; revoked: number } | null;
  criteria?: Record<string, unknown>;
  status?: string;
  createdAt?: Date;
}) {
  const plans = opts.plans ?? [];
  const queryRaw = jest.fn(async () =>
    opts.ledger
      ? [{
          assignment_id: BATCH,
          planned: BigInt(opts.ledger.planned), agents: BigInt(opts.ledger.agents),
          released: BigInt(opts.ledger.released), expired: BigInt(opts.ledger.expired),
          revoked: BigInt(opts.ledger.revoked),
        }]
      : [],
  );
  const prisma = {
    planAssignment: {
      findFirst: jest.fn(async () => ({
        id: BATCH, hostId: 'h1', tenantId: 't1', clinicId: 'c1', createdBy: 'leader-1',
        requestId: 'r1', criteria: opts.criteria ?? {}, attributes: null,
        expiresAt: new Date('2026-08-06T16:00:00Z'), status: opts.status ?? 'confirmed',
        revokedAt: null, revokedBy: null,
        createdAt: opts.createdAt ?? new Date('2026-08-03T13:33:00Z'),
        updatedAt: new Date('2026-08-03T13:33:00Z'),
      })),
      findMany: jest.fn(async () => [{
        id: BATCH, hostId: 'h1', tenantId: 't1', clinicId: 'c1', createdBy: 'leader-1',
        criteria: opts.criteria ?? {}, attributes: null,
        expiresAt: new Date('2026-08-06T16:00:00Z'), status: opts.status ?? 'confirmed',
        createdAt: opts.createdAt ?? new Date('2026-08-03T13:33:00Z'),
      }]),
    },
    followupPlan: {
      findMany: jest.fn(async () =>
        plans.map((p) => ({
          ...p, assignmentId: BATCH, patientId: `pat-${p.id}`, version: 1,
          snoozedUntil: null, assignmentExpiresAt: null,
        })),
      ),
    },
    planEventLog: { findMany: jest.fn(async () => []), groupBy: jest.fn(async () => []) },
    host: { findUnique: jest.fn(async () => ({ pullConfig: { timezone: 'Asia/Shanghai' } })) },
    $queryRaw: queryRaw,
  } as unknown as PrismaService;
  return { prisma, queryRaw };
}

async function build(prisma: PrismaService): Promise<PlanAssignmentService> {
  const mod = await Test.createTestingModule({
    providers: [PlanAssignmentService, { provide: PrismaService, useValue: prisma }],
  })
    .useMocker(() => ({}))
    .compile();
  return mod.get(PlanAssignmentService);
}

describe('批次归因 —— planned 不随重分失血', () => {
  test('⭐⭐ 人被后面的批次挑走后,planned 仍是**当时分的 9**(⛔ 不是现在剩的 2)', async () => {
    const { prisma } = makePrisma({
      // 9 个人里 7 个已被重分走 → followup_plans 只剩 2 条还挂在本批
      plans: [
        { id: 'p1', status: 'assigned', assigneeUserId: 'a', releaseReason: null },
        { id: 'p2', status: 'assigned', assigneeUserId: 'b', releaseReason: null },
      ],
      ledger: { planned: 9, agents: 2, released: 3, expired: 2, revoked: 0 },
    });
    const svc = await build(prisma);
    const d = await svc.detail(SCOPE, BATCH);
    expect(d.planned).toBe(9);
    expect(d.agents).toBe(2);
  });

  test('⭐⭐ 穷尽性:done + inHandPending + backToPool + **reassigned** === planned', async () => {
    // 不补 reassigned 这一桶,主管一对数就发现少了 7 个人,而少的那几个永远查不出去哪了
    const { prisma } = makePrisma({
      plans: [
        { id: 'p1', status: 'assigned', assigneeUserId: 'a', releaseReason: null },
        { id: 'p2', status: 'active', assigneeUserId: null, releaseReason: 'over_capacity' },
      ],
      ledger: { planned: 9, agents: 2, released: 3, expired: 2, revoked: 0 },
    });
    const svc = await build(prisma);
    const p = (await svc.detail(SCOPE, BATCH)).progress;
    expect(p.reassigned).toBe(7);
    expect(p.done + p.inHandPending + p.backToPool + p.reassigned).toBe(9);
  });

  test('⭐ 老批次(账本没记批次号)回落到 followup_plans 现算,⛔ 不显示 0', async () => {
    // 显示一个偏小的数,总好过显示 0 让主管以为这批根本没分成
    const { prisma } = makePrisma({
      plans: [
        { id: 'p1', status: 'assigned', assigneeUserId: 'a', releaseReason: null },
        { id: 'p2', status: 'assigned', assigneeUserId: 'b', releaseReason: null },
      ],
      ledger: null,
    });
    const svc = await build(prisma);
    const d = await svc.detail(SCOPE, BATCH);
    expect(d.planned).toBe(2);
    // ⚠️ 老批次的到期数没有任何可回落的源 → 0,⛔ 不许拿 backToPool 顶替
    expect(d.expired).toBe(0);
  });
});

describe('批次归因 —— 到期与退回必须分开', () => {
  test('⭐⭐ expired 与 released 是两个数(合成一个"回池率"两种病都看不出来)', async () => {
    const { prisma } = makePrisma({
      plans: [{ id: 'p1', status: 'assigned', assigneeUserId: 'a', releaseReason: null }],
      ledger: { planned: 9, agents: 2, released: 3, expired: 2, revoked: 0 },
    });
    const svc = await build(prisma);
    const d = await svc.detail(SCOPE, BATCH);
    expect(d.released).toBe(3);
    expect(d.expired).toBe(2);
  });

  test('⭐ note 要把两者分开说出来 —— 助手是照抄这句话的', async () => {
    const { prisma } = makePrisma({
      plans: [{ id: 'p1', status: 'assigned', assigneeUserId: 'a', releaseReason: null }],
      ledger: { planned: 9, agents: 2, released: 3, expired: 2, revoked: 0 },
    });
    const svc = await build(prisma);
    const note = (await svc.detail(SCOPE, BATCH)).progress.note;
    expect(note).toContain('客服主动退回 3 条');
    expect(note).toContain('到期没人动 2 条');
    expect(note).toContain('处理率不是成功率');
  });
});

describe('批次名 —— 没有列表页时,主管指认一批的唯一抓手', () => {
  test('⭐⭐ 含时间(到分钟)· 治疗项 · **温度** · 人数 · 客服数', async () => {
    const { prisma } = makePrisma({
      plans: [],
      ledger: { planned: 9, agents: 2, released: 0, expired: 0, revoked: 0 },
      criteria: { potentialTreatment: 'perio', temperature: 'warm' },
      createdAt: new Date('2026-08-03T13:33:00Z'), // 东八区 = 8/3 21:33
    });
    const svc = await build(prisma);
    const d = await svc.detail(SCOPE, BATCH);
    expect(d.label).toBe('8/3 21:33 · 牙周治疗 · 窗口内 · 9 人 · 2 位客服');
  });

  test('⭐ 时间按**宿主时区**,⛔ 不是服务器本地时区', async () => {
    // 主管说的"今天下午那批"是他诊所墙上的时间;服务器在别的时区时标签会指向另一天,
    // 而这个名字正是他指认批次的抓手。
    const { prisma } = makePrisma({
      plans: [],
      ledger: { planned: 1, agents: 1, released: 0, expired: 0, revoked: 0 },
      criteria: {},
      createdAt: new Date('2026-08-03T17:00:00Z'), // UTC 8/3 17:00 → 东八区已是 8/4 01:00
    });
    const svc = await build(prisma);
    expect((await svc.detail(SCOPE, BATCH)).label).toContain('8/4 01:00');
  });

  test('⭐ 老批次没存温度 → 那一段**不出现**(⛔ 不许默认填一个)', async () => {
    // 填了会让主管以为那批是按"窗口内"圈的,而他可能圈的是"黄金期"
    const { prisma } = makePrisma({
      plans: [],
      ledger: { planned: 5, agents: 1, released: 0, expired: 0, revoked: 0 },
      criteria: { potentialTreatment: 'implant' },
    });
    const svc = await build(prisma);
    const label = (await svc.detail(SCOPE, BATCH)).label;
    expect(label).toContain('种植治疗');
    expect(label).not.toMatch(/黄金期|窗口内|窗口外/);
  });

  test('已撤销的批次要在名字里标出来 —— 主管扫列表时最先要排除的就是它', async () => {
    const { prisma } = makePrisma({
      plans: [],
      ledger: { planned: 9, agents: 2, released: 0, expired: 0, revoked: 9 },
      status: 'revoked',
    });
    const svc = await build(prisma);
    expect((await svc.detail(SCOPE, BATCH)).label).toContain('已撤销');
  });
});
