'use client';

import type {
  ListPlansQuery,
  ListPlansResponse,
  PlanActionAck,
  PlanCountsResponse,
} from '@pac/types';
import { api } from '@/lib/api-client';
import type { PlanDetailData } from '@/components/plan-detail/plan-detail-types';

export const plansApi = {
  list: (q: Partial<ListPlansQuery>) =>
    api.get<ListPlansResponse>('/pac/v1/plans', {
      query: {
        view: q.view,
        scenario: q.scenario,
        status: q.status,
        targetClinicId: q.targetClinicId,
        assigneeUserId: q.assigneeUserId,
        keyword: q.keyword,
        sort: q.sort,
        page: q.page ?? 1,
        pageSize: q.pageSize ?? 20,
      },
    }),

  /** KPI / Tab badge 聚合计数 — 一次拉齐(替代之前 5 个并发 list 请求)*/
  counts: () => api.get<PlanCountsResponse>('/pac/v1/plans/counts'),

  /** 聚合详情:plan + patient + profile + persona + chains + facts(给 PlanDetailApp 用)*/
  getAggregate: (planId: string) =>
    api.get<PlanDetailData>(`/pac/v1/plans/${encodeURIComponent(planId)}/full`),

  /** 认领 / 指派 — POST /plans/{id}/assign { assigneeUserId } */
  assign: (planId: string, assigneeUserId: string) =>
    api.post<PlanActionAck>(`/pac/v1/plans/${encodeURIComponent(planId)}/assign`, {
      assigneeUserId,
    }),

  /** 回收 — POST /plans/{id}/recycle { reason? }(mine → pool,plan 仍 active)*/
  recycle: (planId: string, reason?: string) =>
    api.post<PlanActionAck>(`/pac/v1/plans/${encodeURIComponent(planId)}/recycle`, {
      reason,
    }),

  /** 拉患者明文手机号(reveal,需 PATIENT_VIEW 权限) — GET /patients/{id}/phone-reveal */
  revealPhone: (patientId: string) =>
    api.get<{ phone: string | null }>(
      `/pac/v1/patients/${encodeURIComponent(patientId)}/phone-reveal`,
    ),
};
