"use client";

import { customFetch } from "@/api/mutator";

type ApiResponse<T> = {
  data: T;
  status: number;
  headers: Headers;
};

export type ClaudeSessionTokens = {
  input: number;
  output: number;
  cache_read: number;
  cache_write: number;
  total: number;
};

export type ClaudeSession = {
  session_id: string;
  project_dir: string;
  cwd: string | null;
  title: string | null;
  models: string[];
  tokens: ClaudeSessionTokens;
  cost_usd: number;
  message_count: number;
  first_message_at: string | null;
  last_message_at: string | null;
  is_active: boolean;
  entrypoints: string[];
  git_branch: string | null;
  version: string | null;
};

export type ClaudeSessionStats = {
  session_count: number;
  active_sessions: number;
  total_tokens: number;
  total_cost_usd: number;
  models: string[];
};

export type ClaudeSessionListResponse = {
  sessions: ClaudeSession[];
  total: number;
  stats: ClaudeSessionStats;
};

export type SessionTextBlock = {
  text: string;
  truncated: boolean;
};

export type SessionThinkingBlock = {
  text: string;
  truncated: boolean;
};

export type SessionToolUseBlock = {
  tool_use_id: string;
  tool_name: string;
  input: Record<string, unknown>;
  input_truncated: boolean;
  result: string | null;
  result_truncated: boolean;
  is_error: boolean;
};

export type SessionTokenUsage = {
  input: number;
  output: number;
  cache_read: number;
  cache_write: number;
};

export type SessionMessage = {
  uuid: string;
  role: "user" | "assistant" | string;
  timestamp: string | null;
  text_blocks: SessionTextBlock[];
  thinking_blocks: SessionThinkingBlock[];
  tool_uses: SessionToolUseBlock[];
  model: string | null;
  tokens: SessionTokenUsage | null;
};

export type SessionMessagesResponse = {
  session_id: string;
  messages: SessionMessage[];
  total: number;
  has_more: boolean;
};

export type ListClaudeSessionsParams = {
  project?: string;
  activeOnly?: boolean;
  limit?: number;
};

export async function listClaudeSessions({
  project,
  activeOnly = false,
  limit = 100,
}: ListClaudeSessionsParams = {}): Promise<ClaudeSessionListResponse> {
  const params = new URLSearchParams();
  if (project?.trim()) params.set("project", project.trim());
  if (activeOnly) params.set("active_only", "true");
  params.set("limit", String(limit));

  const query = params.toString();
  const response = await customFetch<ApiResponse<ClaudeSessionListResponse>>(
    `/api/v1/claude-code/sessions${query ? `?${query}` : ""}`,
    { method: "GET" },
  );
  return response.data;
}

export async function getClaudeSession(
  sessionId: string,
): Promise<ClaudeSession> {
  const response = await customFetch<ApiResponse<ClaudeSession>>(
    `/api/v1/claude-code/sessions/${encodeURIComponent(sessionId)}`,
    { method: "GET" },
  );
  return response.data;
}

export type GetSessionMessagesParams = {
  sessionId: string;
  limit?: number;
  offset?: number;
};

export async function getSessionMessages({
  sessionId,
  limit = 200,
  offset = 0,
}: GetSessionMessagesParams): Promise<SessionMessagesResponse> {
  const params = new URLSearchParams({
    limit: String(limit),
    offset: String(offset),
  });
  const response = await customFetch<ApiResponse<SessionMessagesResponse>>(
    `/api/v1/claude-code/sessions/${encodeURIComponent(sessionId)}/messages?${params.toString()}`,
    { method: "GET" },
  );
  return response.data;
}
