import apiClient from "@/lib/api/client";
import type { ApiResponse, QueryParams } from "@/lib/api/types";
import type {
  CommunityPostDetailRecord,
  CommunityPostRecord,
  CommunityReplyRecord,
  UpdatedCommunityReplyRecord,
} from "@/features/community/communityRecord";

// ─── Posts ───────────────────────────────────────────────────────────────────

/* `index()` builds the resource without `detail:`, so a list row carries **no
   `replies`** — only `replies_count`. `show()` and the two writes below pass
   `detail: true` and do. */
export const getCommunityPosts = (
  params?: QueryParams
): Promise<ApiResponse<CommunityPostRecord[]>> =>
  apiClient.get("/posts/", { params }).then((r) => r.data);

export const getCommunityPostsByTag = ({
  tag,
  page = 1,
  limit = 5,
}: {
  tag: string;
  page?: number;
  limit?: number;
}): Promise<ApiResponse<CommunityPostRecord[]>> =>
  /* `byTag()` merges `tags` into the request and delegates straight to
     `index()`, so the row shape is identical to `getCommunityPosts`. */
  apiClient
    .get("/posts/by_tag/", { params: { tag, page, limit } })
    .then((r) => r.data);

export const getCommunityPostById = (
  id: string
): Promise<ApiResponse<CommunityPostDetailRecord>> =>
  apiClient.get(`/posts/${id}/`).then((r) => r.data);

/* Both writes answer with the **detail** shape (`detail: true` at
   `PostController.php:169` and `:225`), replies included. */
/**
 * `PostController::store()` / `::update()` — multipart in every call.
 *
 * `FormData`, not a `FormData | Record` union: `images[]` is a file array, and the keep-set
 * for an update (`existing_image_ids`) only has a multipart representation.
 * The composition is in `useCreatePostForm`; two rules of it are worth having
 * here because they are both invisible from the key names:
 *
 *  - Laravel's `boolean` rule accepts `1`/`0`, never the strings `"true"` /
 *    `"false"` — `String(true)` 422'd every post from a volunteer or a team,
 *    which is exactly who sees the two toggles;
 *  - the empty keep-set has to travel as the scalar `"none"` sentinel, or
 *    removing the last image reads as "keep everything". See
 *    `features/shared/imageKeepSet`.
 *
 * Both writes answer with the **detail** shape (`detail: true` at
 * `PostController.php:169` and `:225`), replies included — and `store()` adds
 * a `forbidden_words_detected` key when the filter matched, in which case the
 * post is saved with `is_displayed: false`.
 */
export const createCommunityPost = (
  data: FormData
): Promise<ApiResponse<CommunityPostDetailRecord>> =>
  apiClient.post("/posts/", data).then((r) => r.data);

export const updateCommunityPost = ({
  id,
  data,
}: {
  id: string;
  data: FormData;
}): Promise<ApiResponse<CommunityPostDetailRecord>> => {
  // PHP parses multipart bodies only on POST: a real PATCH arrives empty.
  // Laravel reads `_method` off a POST and routes it to the PATCH handler.
  data.set("_method", "PATCH");
  return apiClient.post(`/posts/${id}/`, data).then((r) => r.data);
};

export const deleteCommunityPost = (id: string): Promise<ApiResponse<null>> =>
  apiClient.delete(`/posts/${id}/`).then((r) => r.data);

// ─── Replies ─────────────────────────────────────────────────────────────────

/** Upper bound on pages read for one thread, so a bad `total_pages` cannot loop forever. */
const MAX_REPLY_PAGES = 50;

/**
 * Top-level replies for a post; each carries its own `child_replies`.
 *
 * `ReplyController::index()` **always** paginates (default 20, max 100 per
 * page). Reading only the first page silently dropped every reply after the
 * 20th — and the reply page, which looks its reply up in this tree, bounced
 * back. Every page is read and merged into one envelope.
 */
export const getCommunityReplies = async (
  postId: string
): Promise<ApiResponse<CommunityReplyRecord[]>> => {
  const fetchPage = (page: number): Promise<ApiResponse<CommunityReplyRecord[]>> =>
    apiClient
      .get("/replies/", { params: { post_id: postId, page, limit: 100 } })
      .then((r) => r.data);
  const first = await fetchPage(1);
  const totalPages = Math.min(first.meta?.pagination?.total_pages ?? 1, MAX_REPLY_PAGES);
  const rows = [...(first.data ?? [])];
  for (let page = 2; page <= totalPages; page += 1) {
    const next = await fetchPage(page);
    rows.push(...(next.data ?? []));
  }
  return { ...first, data: rows };
};

export const createCommunityReply = (
  data: FormData
): Promise<ApiResponse<CommunityReplyRecord>> =>
  apiClient.post("/replies/", data).then((r) => r.data);

/*
 * `replies/{id}/` is `match(['put', 'patch'])` with no POST, and the body is
 * multipart (text, `existing_image_ids[]`, `images[]`). PHP only parses a
 * multipart body on POST, so a real PATCH arrives with nothing in `$_POST` or
 * `$_FILES`. Laravel reads `_method` out of the body before routing, so posting
 * with `_method=PATCH` reaches the same PATCH handler with the fields intact —
 * the same workaround `updateLearnServeOpportunity` documents.
 *
 * The reply comes back through `WebsiteReplyResource` — the same shape the
 * list returns — with one extra key spliced on: `mentioned_users`, the @
 * mentions `CommunityMentions::extract()` found in the new text. That is
 * `{ id, username }` per matched user, and only users that exist: the regex
 * collects `@handle` tokens and the result is a `whereIn('username', …)`
 * lookup, so an `@` naming nobody is silently absent rather than echoed back.
 * An empty array, never null.
 *
 * `update()` also refuses, as a **400**, a request that carries neither text,
 * nor a file, nor `existing_image_ids` ("Either text or images must be
 * provided for update."). The keep-set counts as "about the images", which is
 * what lets a reply drop its last image without retyping its text.
 */
export const updateReply = ({
  id,
  formData,
}: {
  id: string;
  formData: FormData;
}): Promise<ApiResponse<UpdatedCommunityReplyRecord>> => {
  formData.append("_method", "PATCH");
  return apiClient.post(`/replies/${id}/`, formData).then((r) => r.data);
};

export const getReplyById = (
  id: string
): Promise<ApiResponse<CommunityReplyRecord>> =>
  apiClient.get(`/replies/${id}/`).then((r) => r.data);

export const deleteReply = (id: string): Promise<ApiResponse<null>> =>
  apiClient.delete(`/replies/${id}/`).then((r) => r.data);

/**
 * Same toggle endpoint backs post likes and reply likes.
 *
 * It is a **toggle**, so the reply is the resulting state rather than a
 * confirmation of what was asked: `is_liked` is what the row now holds and
 * `likes_count` is recounted from the database. The caller should take both
 * from here instead of incrementing its own copy — two taps in flight would
 * otherwise double-count.
 */
export const likeCommunityPost = (data: {
  post_id?: string;
  reply_id?: string;
}): Promise<ApiResponse<{ likes_count: number; is_liked: boolean }>> =>
  apiClient.post("/likes/toggle/", data).then((r) => r.data);

// ─── Contact creator ─────────────────────────────────────────────────────────

/**
 * `PostController::contactCreator()`.
 *
 * `message` is the only validated key — `post_id` travels in the path, and
 * sending it in the body as well is harmless (this controller does not use
 * `RejectsUnknownWriteKeys`).
 *
 * The reply echoes the message back rather than reporting delivery: the
 * controller's own comment says email delivery is handled asynchronously and
 * it "accept[s] the message for API parity". So a success here means accepted,
 * not sent.
 */
export const communityPostContactUs = (data: {
  post_id: string;
  message: string;
}): Promise<ApiResponse<{ post_id: number; message: string }>> =>
  apiClient.post(`/posts/${data.post_id}/contact-creator/`, data).then((r) => r.data);
