import {
  FeedbackSubmitResponse,
  FeedbackSubmitResponseSchema,
  type SubmitFeedbackInput,
} from "@/data/schemas/feedback";

import { ApiPath } from "./api_path";
import { httpClient } from "./http_client";
import { type ApiEnvelope, unwrap } from "./response_helper";

export class FeedbackApi {
  async submit(input: SubmitFeedbackInput): Promise<FeedbackSubmitResponse> {
    const body = new FormData();
    body.append("category", input.category);
    body.append("content", input.content);
    body.append("context", JSON.stringify(input.context));
    input.images.forEach((image) => body.append("images", image));

    const envelope = await httpClient<ApiEnvelope<unknown>>(ApiPath.feedback, {
      method: "POST",
      body,
      ...(input.idempotencyKey
        ? { headers: { "Idempotency-Key": input.idempotencyKey } }
        : {}),
    });
    return FeedbackSubmitResponseSchema.parse(unwrap(envelope));
  }
}

export const feedbackApi = new FeedbackApi();
