// src/api/deal/commentApi.ts
import instance from "../axiosInstance"
import { endpoints } from "@shared/contracts"

const { comments } = endpoints

export async function getComments(dealId: number) {
  try {
    const { data } = await instance.get(`/comments/${dealId}`)
    return comments.commentListResponseSchema.parse(data)
  } catch (error: any) {
    const message = error.response?.data?.error || "Yorumlar alınamadı"
    console.error("Yorumları alma hatası:", message)
    throw new Error(message)
  }
}

export async function postComment(dealId: number, text: string, parentId?: number | null) {
  try {
    const payload: { dealId: number; text: string; parentId?: number | null } = { dealId, text }
    if (typeof parentId === "number") payload.parentId = parentId
    else if (parentId === null) payload.parentId = null

    const { data } = await instance.post("/comments", payload)
    return comments.commentCreateResponseSchema.parse(data)
  } catch (error: any) {
    const message = error.response?.data?.error || "Yorum gönderilemedi"
    console.error("Yorum gönderme hatası:", message)
    throw new Error(message)
  }
}


export async function deleteComment(commentId: number) {
  try {
    const { data } = await instance.delete(`/comments/${commentId}`)
    return comments.commentDeleteResponseSchema.parse(data)
  } catch (error: any) {
    const message =
      error.response?.data?.error ||
      (error.response?.status === 403 ? "Bu yorumu silmeye yetkin yok" : "Yorum silinemedi")
    console.error("Yorum silme hatası:", message)
    throw new Error(message)
  }
}