import { demoCards } from './demoFixtures';
import { buildAuthHeaders } from './hmac';
import type { CardInstance } from './types';

const API_BASE = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:6040/api/v1';
const DEMO_MODE = import.meta.env.VITE_DEMO_MODE === 'true';

function isSuccess(body: { code: unknown }): boolean {
  return body.code === 0 || body.code === 200;
}

export async function fetchCard(cardInstanceId: string): Promise<CardInstance> {
  if (DEMO_MODE) {
    const card = demoCards[cardInstanceId];
    if (!card) throw new Error(`演示卡片不存在: ${cardInstanceId}`);
    return card;
  }

  const path = `/api/v1/cards/${cardInstanceId}`;
  const headers = await buildAuthHeaders('GET', path, '');
  const response = await fetch(`${API_BASE}/cards/${cardInstanceId}`, { headers });
  const body = await response.json();
  if (!response.ok || !isSuccess(body)) throw new Error(body.msg ?? '查询卡片失败');
  return body.data;
}

export interface CardActionResult {
  status: string;
  actionId: string;
  nextCard?: CardInstance;
}

export async function submitCardAction(
  cardInstanceId: string,
  actionName: string,
  payload: Record<string, unknown>,
  idempotencyKey?: string,
): Promise<CardActionResult> {
  const key = idempotencyKey ?? `${cardInstanceId}-${actionName}-${Date.now()}`;
  const body = JSON.stringify({
    idempotencyKey: key,
    confirm: true,
    payload,
  });

  if (DEMO_MODE) {
    return { status: 'completed', actionId: `action_${Date.now()}` };
  }

  const path = `/api/v1/cards/${cardInstanceId}/actions/${actionName}`;
  const headers = await buildAuthHeaders('POST', path, body);
  const response = await fetch(`${API_BASE}/cards/${cardInstanceId}/actions/${actionName}`, {
    method: 'POST',
    headers: { ...headers, 'Content-Type': 'application/json' },
    body,
  });
  const data = await response.json();
  if (!response.ok || !isSuccess(data)) throw new Error(data.msg ?? '提交卡片动作失败');
  return data.data;
}
