import { Injectable, Logger, NotFoundException, BadRequestException } from '@nestjs/common';
import { EXECUTION_OUTCOME_META, ExecutionOutcome } from '@pac/types';
import { PrismaService } from '../../prisma/prisma.service';
import type { TenantScopeContext } from '../../common/decorators/tenant-scope.decorator';

/**
 * ExecutionService — PlanExecution 回写 + Plan 状态机 + 熔断检查
 *
 * 触发路径(spec three-layer-model § "PlanExecution 回写"):
 *   客服工作台 → POST /pac/v1/.../plans/{id}/executions
 *      ↓
 *   1) 校验 plan 存在 + 仍可写(active/assigned)
 *   2) plan_executions 写一行(append-only,不更新)
 *   3) followup_plans.contactAttempts++
 *   4) 按 outcome 决定 plan.status 新值(见 OUTCOME_TO_STATUS)
 *   5) 熔断:若 contactAttempts >= maxContactAttempts 且未 completed → 强制 abandoned
 *   6) 返回 executionId + 新 plan.status(让前端无需重拉)
 *
 * 单向数据流:本服务**不回写 patient_facts / patient_transactions**(spec v1 纪律)。
 * 召回成功新预约靠下次 pull 时 patient_transactions 自动反映,不在本表立柱关联。
 */

const MAX_CONTACT_ATTEMPTS_DEFAULT = 4; // 暂常量,后续接 host/scenario 配置

/**
 * outcome → plan.status 映射(spec § "按 outcome 驱动 Plan.status"):
 *   completed   = 闭环成功 / 不再需要召回(转化 / 外院 / 明确拒绝 / 无效)
 *   abandoned   = 客服主动放弃
 *   keep        = 维持当前 status(等下次或下次回访)
 */
type StatusTransition = 'completed' | 'abandoned' | 'keep';

/**
 * outcome → 状态机映射 — **派生自 @pac/types 单一真理源**
 *
 * 老版本(W4 早期)在这里 hardcode 一份 OUTCOME_TO_STATUS,前端 mock-data
 * 也单独维护一份 `drives` 字段,3 处口径漂移已踩过坑。
 * 现在统一从 EXECUTION_OUTCOME_META.drivesStatus 派生,改一处全生效。
 */
const OUTCOME_TO_STATUS: Record<string, StatusTransition> = Object.fromEntries(
  Object.entries(EXECUTION_OUTCOME_META).map(([k, v]) => [k, v.drivesStatus]),
);

export interface SubmitExecutionInput {
  channel: string;
  outcome: string;
  notes?: string;
  abandonReasons?: string[];
  abandonOther?: string;
  scheduledNextAt?: string;
  invalidReason?: string;
  /** 显式覆盖执行诊所;不传则用 plan.targetClinicId 或 scope 第一个 clinicId */
  executorClinicId?: string;
}

export interface SubmitExecutionResult {
  executionId: string;
  planStatus: string;
  contactAttempts: number;
  breakerTripped: boolean;
}

@Injectable()
export class ExecutionService {
  private readonly logger = new Logger(ExecutionService.name);

  constructor(private readonly prisma: PrismaService) {}

  async submit(
    scope: TenantScopeContext,
    planId: string,
    operatorUserId: string,
    input: SubmitExecutionInput,
  ): Promise<SubmitExecutionResult> {
    // ─── 1. 校验 plan ───
    const plan = await this.prisma.followupPlan.findUnique({
      where: { id: planId },
      select: {
        id: true,
        hostId: true,
        tenantId: true,
        patientId: true,
        status: true,
        contactAttempts: true,
        targetClinicId: true,
      },
    });
    if (!plan) throw new NotFoundException(`Plan ${planId} not found`);
    if (plan.hostId !== scope.hostId || plan.tenantId !== scope.tenantId) {
      throw new NotFoundException(`Plan ${planId} not found`);  // 跨 tenant 故意伪装 404
    }
    if (plan.status !== 'active' && plan.status !== 'assigned') {
      throw new BadRequestException(
        `Plan ${planId} 当前状态 ${plan.status},不可写 execution`,
      );
    }

    // ─── 2. 解析 executorClinicId ───
    const executorClinicId =
      input.executorClinicId ??
      plan.targetClinicId ??
      scope.clinicIds[0] ??
      'demo-clinic';

    // ─── 3. 解析 outcome → 新 status ───
    const transition = OUTCOME_TO_STATUS[input.outcome];
    if (!transition) {
      throw new BadRequestException(`未知 outcome=${input.outcome}`);
    }

    const nextContactAttempts = plan.contactAttempts + 1;
    let newStatus: string = plan.status;
    let breakerTripped = false;

    if (transition === 'completed') {
      newStatus = 'completed';
    } else if (transition === 'abandoned') {
      newStatus = 'abandoned';
    } else {
      // keep:status 不变,但要检查熔断
      if (nextContactAttempts >= MAX_CONTACT_ATTEMPTS_DEFAULT) {
        newStatus = 'abandoned';
        breakerTripped = true;
        this.logger.warn(
          `plan=${planId} 熔断:contactAttempts=${nextContactAttempts} >= ${MAX_CONTACT_ATTEMPTS_DEFAULT},强制 abandoned`,
        );
      }
    }

    // ─── 4. 事务:写 execution + 更新 plan ───
    const result = await this.prisma.$transaction(async (tx) => {
      const execution = await tx.planExecution.create({
        data: {
          hostId: plan.hostId,
          tenantId: plan.tenantId,
          executorClinicId,
          planId: plan.id,
          operatorUserId,
          channel: input.channel,
          outcome: input.outcome,
          notes: input.notes ?? null,
          invalidReason: input.invalidReason ?? null,
          abandonReasons: input.abandonReasons ?? [],
          abandonOther: input.abandonOther ?? null,
          scheduledNextAt: input.scheduledNextAt ? new Date(input.scheduledNextAt) : null,
        },
        select: { id: true },
      });

      await tx.followupPlan.update({
        where: { id: plan.id },
        data: {
          status: newStatus,
          contactAttempts: nextContactAttempts,
          // 终态额外清理 assignee(让 plan 离开"我的工单"列表)
          ...(newStatus === 'completed' || newStatus === 'abandoned'
            ? { assigneeUserId: null, assignedAt: null, recycleAt: null }
            : {}),
        },
      });

      return execution;
    }, { maxWait: 30000, timeout: 60000 });

    return {
      executionId: result.id,
      planStatus: newStatus,
      contactAttempts: nextContactAttempts,
      breakerTripped,
    };
  }

  /**
   * 列出某 plan 的执行历史(给"通话记录"面板用)
   */
  async list(scope: TenantScopeContext, planId: string) {
    const plan = await this.prisma.followupPlan.findUnique({
      where: { id: planId },
      select: { id: true, hostId: true, tenantId: true },
    });
    if (!plan || plan.hostId !== scope.hostId || plan.tenantId !== scope.tenantId) {
      throw new NotFoundException(`Plan ${planId} not found`);
    }
    const executions = await this.prisma.planExecution.findMany({
      where: { planId },
      orderBy: { createdAt: 'desc' },
    });
    return executions.map((e) => ({
      id: e.id,
      hostId: e.hostId,
      tenantId: e.tenantId,
      planId: e.planId,
      executorClinicId: e.executorClinicId,
      operatorUserId: e.operatorUserId,
      channel: e.channel,
      outcome: e.outcome as ExecutionOutcome,
      notes: e.notes,
      invalidReason: e.invalidReason,
      abandonReasons: e.abandonReasons,
      abandonOther: e.abandonOther,
      scheduledNextAt: e.scheduledNextAt?.toISOString() ?? null,
      createdAt: e.createdAt.toISOString(),
    }));
  }
}
