/**
 * Post API — CRUD for creator posts + file upload/download.
 */

import { BASE, request, requestMultipart } from "./client";

// ── Types ───────────────────────────────────────────────────────────────────

export interface PostAttachmentRead {
  id: string;
  filename: string;
  content_type: string;
  size_bytes: number;
  download_url: string | null;
  created_at: string;
}

export interface PostRead {
  id: string;
  creator_id: string;
  title: string;
  body_json: Record<string, unknown>;
  is_published: boolean;
  created_at: string;
  updated_at: string;
  attachments: PostAttachmentRead[];
}

export interface PostCreate {
  title: string;
  body_json: Record<string, unknown>;
  is_published?: boolean;
}

export interface PostUpdate {
  title?: string;
  body_json?: Record<string, unknown>;
  is_published?: boolean;
}

export interface PostListResponse {
  items: PostRead[];
  total: number;
}

// ── API Functions ───────────────────────────────────────────────────────────

export function createPost(data: PostCreate): Promise<PostRead> {
  return request<PostRead>(`${BASE}/posts`, {
    method: "POST",
    body: JSON.stringify(data),
  });
}

export function updatePost(id: string, data: PostUpdate): Promise<PostRead> {
  return request<PostRead>(`${BASE}/posts/${id}`, {
    method: "PUT",
    body: JSON.stringify(data),
  });
}

export function getPost(id: string): Promise<PostRead> {
  return request<PostRead>(`${BASE}/posts/${id}`);
}

export function listPosts(
  creatorId: string,
  page = 1,
  limit = 20,
): Promise<PostListResponse> {
  return request<PostListResponse>(
    `${BASE}/posts?creator_id=${creatorId}&page=${page}&limit=${limit}`,
  );
}

export function uploadFile(
  postId: string,
  file: File,
): Promise<PostAttachmentRead> {
  const form = new FormData();
  form.append("file", file);
  form.append("post_id", postId);
  return requestMultipart<PostAttachmentRead>(`${BASE}/files/upload`, form);
}

export function getDownloadUrl(
  attachmentId: string,
): Promise<{ url: string; filename: string }> {
  return request<{ url: string; filename: string }>(
    `${BASE}/files/${attachmentId}/download`,
  );
}

export function deletePost(id: string): Promise<void> {
  return request<void>(`${BASE}/posts/${id}`, { method: "DELETE" });
}
