import { api } from '../core/api';
import type {
  TradeItemDTO,
  TradeItemDetailDTO,
  CreateTradeItemInput,
  UpdateTradeItemInput,
  TradeCursorPageResponse,
  TradeType,
  TradeCategory,
  TradeItemStatus,
} from '@/types/trade';

class TradeService {
  async getTradeItems(params?: {
    trade_type?: TradeType;
    category?: TradeCategory;
    status?: TradeItemStatus;
    keyword?: string;
    cursor?: string;
    page_size?: number;
  }): Promise<TradeCursorPageResponse> {
    const queryParams: Record<string, string> = {};
    if (params?.trade_type) queryParams.trade_type = params.trade_type;
    if (params?.category) queryParams.category = params.category;
    if (params?.status) queryParams.status = params.status;
    if (params?.keyword) queryParams.keyword = params.keyword;
    if (params?.cursor) queryParams.cursor = params.cursor;
    if (params?.page_size) queryParams.page_size = String(params.page_size);

    const res = await api.get<TradeCursorPageResponse>('/trade', queryParams);
    return res.data;
  }

  async getTradeItem(id: string): Promise<TradeItemDetailDTO> {
    const res = await api.get<TradeItemDetailDTO>(`/trade/${id}`);
    return res.data;
  }

  async createTradeItem(data: CreateTradeItemInput): Promise<TradeItemDetailDTO> {
    const res = await api.post<TradeItemDetailDTO>('/trade', data);
    return res.data;
  }

  async updateTradeItem(id: string, data: UpdateTradeItemInput): Promise<TradeItemDetailDTO> {
    const res = await api.put<TradeItemDetailDTO>(`/trade/${id}`, data);
    return res.data;
  }

  async deleteTradeItem(id: string): Promise<void> {
    await api.delete(`/trade/${id}`);
  }

  async updateTradeItemStatus(id: string, status: TradeItemStatus): Promise<void> {
    await api.put(`/trade/${id}/status`, { status });
  }

  async recordView(id: string): Promise<void> {
    await api.post(`/trade/${id}/view`, {});
  }

  async favorite(id: string): Promise<{ favorited: boolean }> {
    const res = await api.post<{ favorited: boolean }>(`/trade/${id}/favorite`, {});
    return res.data;
  }

  async unfavorite(id: string): Promise<{ favorited: boolean }> {
    const res = await api.delete<{ favorited: boolean }>(`/trade/${id}/favorite`);
    return res.data;
  }
}

export const tradeService = new TradeService();