import { useMutation } from "@tanstack/react-query"
import { supabase } from "@/lib/supabase"
import { canUseWritingCheck, recordWritingCheckUsage } from "@/utils/rate-limiter"

interface WritingFeedback {
  score: string
  grammar: string[]
  vocabulary: string[]
  structure: string
  improved_version: string
  summary: string
}

export function useWritingCheck() {
  return useMutation({
    mutationFn: async (content: string): Promise<WritingFeedback> => {
      if (!canUseWritingCheck()) {
        throw new Error("Bạn đã dùng hết 3 lần kiểm tra hôm nay. Quay lại vào ngày mai!")
      }
      const { data, error } = await supabase.functions.invoke("writing-check", {
        body: { content },
      })
      if (error) throw error
      recordWritingCheckUsage()
      return data as WritingFeedback
    },
  })
}
