'use client';

import { api } from '@/lib/api-client';

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

export interface SubmitExecutionBody {
  channel: string;
  outcome: string;
  notes?: string;
  abandonReasons?: string[];
  abandonOther?: string;
  scheduledNextAt?: string;
  /** 关闭机会来源(宿主回访模式弹窗)—— 服务端据此覆写抑制窗 */
  closeReason?: string;
}

/**
 * 中文 → 后端 AbandonReason enum 的映射。
 * UI 给客服显示中文便于选,后端要 enum 入库。匹配不上的归 'other' 并把原文塞 abandonOther。
 */
const ABANDON_REASON_MAP: Record<string, string> = {
  '号码空号 / 错号': 'wrong_number',
  '已转介他人': 'treated_elsewhere',
  '明确不需要治疗': 'patient_refused',
  '迁居外地': 'out_of_service_area',
  '投诉 / 不愿打扰': 'do_not_contact_request',
};

export function submitExecution(planId: string, body: SubmitExecutionBody) {
  return api.post<SubmitExecutionResult>(
    `/pac/v1/plans/${encodeURIComponent(planId)}/executions`,
    body,
  );
}

/**
 * 把 UI 的中文原因数组转换成 backend 的 (enum 数组, abandonOther 字符串) 二元组。
 */
export function adaptAbandonReasons(zhReasons: string[]): {
  abandonReasons: string[];
  abandonOther: string | undefined;
} {
  const mapped: string[] = [];
  const otherTexts: string[] = [];
  for (const z of zhReasons) {
    const code = ABANDON_REASON_MAP[z];
    if (code) {
      mapped.push(code);
    } else {
      // '其他' 或自定义文案,统一打成 'other' enum + 原文留底
      if (!mapped.includes('other')) mapped.push('other');
      otherTexts.push(z);
    }
  }
  return {
    abandonReasons: mapped,
    abandonOther: otherTexts.length > 0 ? otherTexts.join('; ') : undefined,
  };
}
