import { apiRequest } from "@/lib/queryClient";

export type StrategyFrequencyUnit = "days" | "minutes";

export type StrategyStartRequest = {
  strategy_name: string;
  sip_amount: number;
  sip_frequency: {
    value: number;
    unit: StrategyFrequencyUnit;
  };
  mode: "LIVE" | "PAPER";
  initial_cash?: number;
};

export type StrategyActionResponse = {
  status: string;
  run_id?: string | null;
  message?: string;
  redirect_url?: string | null;
  broker?: string | null;
  warning?: string;
};

export type StrategyStatusResponse = {
  status?: string;
  last_updated?: string | null;
  last_execution_ts?: string | null;
  next_eligible_ts?: string | null;
  run_id?: string | null;
  can_resume?: boolean;
  can_restart?: boolean;
  config?: {
    strategy?: string | null;
    sip_amount?: number | null;
    sip_frequency?: {
      value?: number | null;
      unit?: StrategyFrequencyUnit | null;
    } | null;
    mode?: string | null;
    broker?: string | null;
    active?: boolean | null;
  } | null;
};

export async function startStrategy(data: StrategyStartRequest): Promise<StrategyActionResponse> {
  const res = await apiRequest("POST", "/strategy/start", data);
  return res.json();
}

export async function stopStrategy(): Promise<StrategyActionResponse> {
  const res = await apiRequest("POST", "/strategy/stop");
  return res.json();
}

export async function resumeStrategy(): Promise<StrategyActionResponse> {
  const res = await apiRequest("POST", "/strategy/resume");
  return res.json();
}

export async function getStrategyStatus(): Promise<StrategyStatusResponse> {
  const res = await apiRequest("GET", "/strategy/status");
  return res.json();
}
