import client from '../client';

/* ── Types ── */

export type WsStatus =
  | 'draft' | 'planning' | 'planned'
  | 'applying' | 'applied'
  | 'destroying' | 'destroyed'
  | 'failed';

export interface Workspace {
  id: string;
  name: string;
  session_id: string;
  session_title?: string;
  oci_config_id: string;
  compartment_id?: string;
  status: WsStatus;
  plan_output?: string;
  apply_output?: string;
  destroy_output?: string;
  error?: string;
  tf_code?: string;
  created_at: string;
  updated_at: string;
}

export interface WsStatusResult {
  status: WsStatus;
  plan_output?: string;
  apply_output?: string;
  destroy_output?: string;
  error?: string;
  updated_at: string;
}

export interface ChatSession {
  id: string;
  title: string;
  agent_type: string;
  created_at: string;
  updated_at: string;
}

export interface ChatMessage {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  created_at?: string;
}

export interface PromptResponse {
  message_id: string;
  session_id: string;
  status: 'processing' | 'done';
  prompt?: string;
}

export interface MessageStatus {
  status: 'processing' | 'done' | 'failed';
  content: string;
}

/* ── Workspace API ── */

export const terraformApi = {
  /* Workspaces */
  listWorkspaces: () =>
    client.get('/terraform/workspaces') as unknown as Promise<Workspace[]>,

  getWorkspace: (wid: string) =>
    client.get(`/terraform/workspaces/${wid}`) as unknown as Promise<Workspace>,

  deleteWorkspace: (wid: string) =>
    client.delete(`/terraform/workspaces/${wid}`) as unknown as Promise<{ ok: boolean }>,

  plan: (wid: string) =>
    client.post(`/terraform/workspaces/${wid}/plan`) as unknown as Promise<{ status: string }>,

  apply: (wid: string) =>
    client.post(`/terraform/workspaces/${wid}/apply`) as unknown as Promise<{ status: string }>,

  destroy: (wid: string) =>
    client.post(`/terraform/workspaces/${wid}/destroy`, { confirm: 'DESTROY' }) as unknown as Promise<{ status: string }>,

  cancel: (wid: string) =>
    client.post(`/terraform/workspaces/${wid}/cancel`) as unknown as Promise<{ ok: boolean }>,

  status: (wid: string) =>
    client.get(`/terraform/workspaces/${wid}/status`) as unknown as Promise<WsStatusResult>,

  downloadUrl: (wid: string) => {
    const token = localStorage.getItem('t') || '';
    return `/api/terraform/workspaces/${wid}/download?token=${encodeURIComponent(token)}`;
  },

  /* Prompt Generator */
  generatePrompt: (body: {
    message: string;
    session_id?: string;
    genai_config: Record<string, string | undefined>;
    history?: { role: string; content: string }[] | null;
  }) =>
    client.post('/terraform/generate-prompt', body) as unknown as Promise<PromptResponse>,

  /* Chat sessions / history */
  listSessions: (agentType: string, limit = 50) =>
    client.get(`/chat/sessions?agent_type=${agentType}&limit=${limit}`) as unknown as Promise<ChatSession[]>,

  loadSession: (sid: string) =>
    client.get(`/chat/sessions/${sid}/messages`) as unknown as Promise<{ messages: ChatMessage[] }>,

  deleteSession: (sid: string) =>
    client.delete(`/chat/sessions/${sid}`) as unknown as Promise<{ ok: boolean }>,

  pollMessageStatus: (mid: string) =>
    client.get(`/chat/${mid}/status`) as unknown as Promise<MessageStatus>,

  createWorkspace: (body: { session_id?: string; oci_config_id: string; compartment_id?: string; name: string; tf_code: string }) =>
    client.post('/terraform/workspaces', body) as unknown as Promise<Workspace>,

  updateCode: (wid: string, tf_code: string) =>
    client.put(`/terraform/workspaces/${wid}/code`, { tf_code }) as unknown as Promise<{ ok: boolean }>,

  chat: (body: { message: string; session_id?: string; genai_config_id?: string; model_id?: string; oci_config_id?: string; genai_region?: string; compartment_id?: string; temperature?: number; max_tokens?: number; use_tools?: boolean }) =>
    client.post('/terraform/chat', body) as unknown as Promise<{ message_id: string; session_id: string; status: string }>,

  loadResources: (ociConfigId: string, compartmentId: string, region?: string) => {
    const params = new URLSearchParams({ oci_config_id: ociConfigId, compartment_id: compartmentId });
    if (region) params.set('region', region);
    return client.get(`/terraform/resources?${params}`) as unknown as Promise<Record<string, any[]>>;
  },

  getCompartmentTree: (cid: string) =>
    client.get(`/oci/explore/${cid}/compartment-tree`) as unknown as Promise<any[]>,
};
