import { api } from "@/lib/api-client";
import type { PaginatedResponse } from "@/types/common";
import type {
  AIFeedback,
  AIFeedbackStatus,
  AIFeedbackSubjectType,
  AIFeedbackSubmitInput,
  AIFeedbackSummary,
} from "@/types/ai-feedback";

export const aiFeedbackService = {
  async submit(input: AIFeedbackSubmitInput): Promise<AIFeedback> {
    return api.post<AIFeedback>("/ai/feedback", input);
  },

  async summary(
    subjectType: AIFeedbackSubjectType,
    subjectId: number,
  ): Promise<AIFeedbackSummary> {
    return api.get<AIFeedbackSummary>("/ai/feedback/summary", {
      subject_type: subjectType,
      subject_id: subjectId,
    });
  },

  async list(
    params: {
      status?: AIFeedbackStatus;
      rating?: "up" | "down";
      subject_type?: AIFeedbackSubjectType;
      prompt_key?: string;
      page?: number;
      size?: number;
    } = {},
  ): Promise<PaginatedResponse<AIFeedback>> {
    const res = await api.get<PaginatedResponse<AIFeedback>>("/ai/feedback", params);
    const items = res.items ?? res.data ?? [];
    return {
      items,
      total: res.total ?? items.length,
      page: res.page ?? 1,
      size: res.size ?? items.length,
      pages: res.pages ?? 1,
    };
  },

  async resolve(
    id: number,
    status: Exclude<AIFeedbackStatus, "open">,
    notes?: string,
  ): Promise<AIFeedback> {
    return api.post<AIFeedback>(`/ai/feedback/${id}/resolve`, { status, notes });
  },
};
