import client, { apiPrefix, unwrap, type ApiResponse } from './client'

export type Stock = Record<string, unknown> & { id: number; state: string; statusLabel: string }
export type StockSearch = { total: number; list: Stock[]; counts: Record<string, number> }

export type StockHistoryItem = {
  id: number
  processDate?: string
  statusLabel?: string
  companyLabel?: string
  processor?: string
}

export type StockNoteItem = {
  id: number
  stockId?: number
  contents?: string
  authorName?: string
  noteDate?: string
}

export type StockDetail = {
  stock: Stock
  histories: StockHistoryItem[]
  notes: StockNoteItem[]
}

export const stockApi = {
  async search(params: Record<string, unknown>) {
    const { data } = await client.get<ApiResponse<StockSearch>>(`${apiPrefix()}/stocks/search`, { params })
    return unwrap(data)
  },
  async detail(id: number) {
    const { data } = await client.get<ApiResponse<StockDetail>>(`${apiPrefix()}/stocks/${id}/detail`)
    return unwrap(data)
  },
  async save(id: number, payload: Record<string, unknown>) {
    const { data } = await client.put<ApiResponse<StockDetail>>(`${apiPrefix()}/stocks/${id}`, payload)
    return unwrap(data)
  },
  async create(payload: Record<string, unknown>) {
    const { data } = await client.post<ApiResponse<StockDetail | Stock>>(`${apiPrefix()}/stocks`, payload)
    return unwrap(data)
  },
  async remove(id: number) {
    const { data } = await client.delete<ApiResponse>(`${apiPrefix()}/stocks/${id}`)
    return unwrap(data)
  },
  async action(id: number, payload: Record<string, unknown>) {
    const { data } = await client.post<ApiResponse<StockDetail>>(`${apiPrefix()}/stocks/${id}/action`, payload)
    return unwrap(data)
  },
  async addNote(id: number, payload: { contents: string; authorName?: string }) {
    const { data } = await client.post<ApiResponse<StockNoteItem>>(`${apiPrefix()}/stocks/${id}/notes`, payload)
    return unwrap(data)
  },
  async deleteNote(id: number, noteId: number) {
    const { data } = await client.delete<ApiResponse>(`${apiPrefix()}/stocks/${id}/notes/${noteId}`)
    return unwrap(data)
  },
  async bulkIn(payload: Record<string, unknown>) {
    const { data } = await client.post<ApiResponse>(`${apiPrefix()}/stocks/bulk-in`, payload)
    return unwrap(data)
  },
  async bulkAction(ids: number[], state: string) {
    const { data } = await client.post<ApiResponse>(`${apiPrefix()}/stocks/bulk-action`, { ids, state })
    return unwrap(data)
  },
  async sheet(params: Record<string, unknown>) {
    const { data } = await client.get<ApiResponse<StockSearch>>(`${apiPrefix()}/stocks/sheet`, { params })
    return unwrap(data)
  },
  exportUrl(params: Record<string, unknown>) {
    const query = new URLSearchParams(Object.entries(params).filter(([, value]) => value !== undefined && value !== '').map(([key, value]) => [key, String(value)]))
    return `${apiPrefix()}/stocks/export?${query}`
  },
}
