import { buildQuery, request } from './client'

export type MessageRole = 'user' | 'assistant'
export type MessageStatus = 'pending' | 'ok' | 'error' | 'cancelled'
export type TemplateScope = 'system' | 'user'

export interface Conversation {
  id: string
  user_id: string
  project_id?: string | null
  workspace_id?: string | null
  issue_id?: string | null
  requirement_id?: string | null
  model_id: string
  system_prompt: string
  title?: string | null
  created_at: string
  updated_at: string
}

export interface Attachment {
  id: string
  filename: string
  mime_type: string
  size_bytes: number
  sha256: string
  created_at: string
}

export interface ChatMessage {
  id: number
  conversation_id: string
  role: MessageRole
  content: string
  thinking?: string | null
  status: MessageStatus
  error_message?: string | null
  prompt_tokens?: number | null
  completion_tokens?: number | null
  thinking_tokens?: number | null
  attachments?: Attachment[]
  created_at: string
  updated_at: string
}

export interface PromptTemplate {
  id: string
  name: string
  content: string
  scope: TemplateScope
  owner_id?: string | null
  created_at: string
  updated_at: string
}

export interface ConversationDetail {
  conversation: Conversation
  messages: ChatMessage[]
}

export interface SendMessageResp {
  user_message_id: number
  assistant_message_id: number
  stream_url: string
}

export interface RetryMessageResp {
  assistant_message_id: number
  stream_url: string
}

export interface ListConversationsParams {
  project_id?: string
  workspace_id?: string
  issue_id?: string
  requirement_id?: string
  q?: string
  limit?: number
}

export interface CreateConversationBody {
  model_id: string
  template_id?: string
  system_prompt?: string
  project_id?: string
  workspace_id?: string
  issue_id?: string
  requirement_id?: string
}

export interface UsageDailyItem {
  day: string
  prompt_tokens: number
  completion_tokens: number
  thinking_tokens: number
  cost_usd: number
}

const enc = (v: string) => encodeURIComponent(v)

export const chatApi = {
  // ===== Conversations =====
  listConversations: (params: ListConversationsParams = {}) =>
    request<Conversation[]>(`/api/v1/conversations${buildQuery(params)}`),
  createConversation: (body: CreateConversationBody) =>
    request<Conversation>('/api/v1/conversations', { method: 'POST', body }),
  getConversation: (id: string, opts: { limit?: number } = {}) =>
    request<ConversationDetail>(
      `/api/v1/conversations/${enc(id)}${buildQuery({
        limit: opts.limit ?? 50,
      })}`,
    ),
  updateConversationTitle: (id: string, title: string) =>
    request<void>(`/api/v1/conversations/${enc(id)}`, {
      method: 'PATCH',
      body: { title },
    }),
  deleteConversation: (id: string) =>
    request<void>(`/api/v1/conversations/${enc(id)}`, { method: 'DELETE' }),

  // ===== Messages =====
  sendMessage: (
    conversationId: string,
    body: { content: string; attachment_ids?: string[] },
  ) =>
    request<SendMessageResp>(`/api/v1/conversations/${enc(conversationId)}/messages`, {
      method: 'POST',
      body,
    }),
  listMessages: (
    id: string,
    params: { before_id?: number; limit?: number } = {},
  ) =>
    request<ChatMessage[]>(
      `/api/v1/conversations/${enc(id)}/messages${buildQuery({
        before_id: params.before_id,
        limit: params.limit,
      })}`,
    ),
  cancelMessage: (messageId: number) =>
    request<void>(`/api/v1/messages/${messageId}/cancel`, { method: 'POST' }),
  retryMessage: (messageId: number) =>
    request<RetryMessageResp>(`/api/v1/messages/${messageId}/retry`, { method: 'POST' }),

  // ===== Uploads =====
  uploadAttachment: (file: File) => {
    const fd = new FormData()
    fd.append('file', file)
    return request<Attachment>('/api/v1/uploads', { method: 'POST', body: fd })
  },

  // ===== Templates =====
  listTemplates: () => request<PromptTemplate[]>('/api/v1/prompt-templates'),
  createTemplate: (body: { name: string; content: string; scope: TemplateScope }) =>
    request<PromptTemplate>('/api/v1/prompt-templates', { method: 'POST', body }),
  updateTemplate: (id: string, body: { name?: string; content?: string }) =>
    request<void>(`/api/v1/prompt-templates/${enc(id)}`, { method: 'PATCH', body }),
  deleteTemplate: (id: string) =>
    request<void>(`/api/v1/prompt-templates/${enc(id)}`, { method: 'DELETE' }),

  // ===== Personal usage =====
  myDailyUsage: (from: string, to: string) =>
    request<UsageDailyItem[]>(`/api/v1/users/me/usage${buildQuery({ from, to })}`),
}
