import { type Attachment } from "@/types/proto/api/v1/attachment_service_pb";
import { fetchJson } from "./apiClient";
import { attachmentFromApi } from "./converters";
import type { ApiAttachment } from "./types";

export const attachmentServiceClient = {
  async listAttachments(_request?: unknown): Promise<{ attachments: Attachment[]; nextPageToken: string; totalSize: number }> {
    void _request;
    const data = await fetchJson<ApiAttachment[]>("/attachments", { method: "GET" });
    const attachments = Array.isArray(data) ? data.map(attachmentFromApi) : [];
    return { attachments, nextPageToken: "", totalSize: attachments.length };
  },
  async createAttachment(request: { attachment?: Attachment }): Promise<Attachment> {
    const attachment = request.attachment;
    if (!attachment) {
      throw new Error("Missing attachment payload");
    }
    const content = attachment.content || new Uint8Array();
    const fileType = attachment.type || "application/octet-stream";
    const filename = attachment.filename || "upload.bin";
    const formData = new FormData();
    formData.append("file", new Blob([content], { type: fileType }), filename);
    const data = await fetchJson<ApiAttachment>("/attachments", { method: "POST", body: formData });
    const mapped = attachmentFromApi(data);
    return {
      ...mapped,
      type: attachment.type || "",
      size: attachment.size || BigInt(0),
    };
  },
  async deleteAttachment(_request: { name: string }): Promise<void> {
    void _request;
    return;
  },
};

