import apiClient from "@/lib/api/client";
import type { ApiResponse, QueryParams } from "@/lib/api/types";
import type {
  AdminEventRecord,
  EventDetailRecord,
  EventRecord,
} from "@/features/events/eventRecord";

// ─── Events ──────────────────────────────────────────────────────────────────

/* `index()` builds `WebsiteEventResource` without `detail:`, `show()` with it —
   hence the two record types. */
export const getAllEvents = (
  params?: QueryParams
): Promise<ApiResponse<EventRecord[]>> =>
  apiClient.get("/events/", { params }).then((r) => r.data);

/*
 * `pass_token` is **not read anywhere in the backend**.
 *
 * Grepping the whole of `fursa_backend/app` for it finds exactly one hit: the
 * allow-list in `RejectsUnknownWriteKeys`, which applies to writes only. Both
 * controllers below authorize from `$request->user()`, which the axios
 * interceptor already populates by attaching `Authorization: Token …` whenever
 * `authStore` holds one — so the creator-only fields arrive for a signed-in
 * reader with or without this parameter.
 *
 * The parameter and the `passToken` / second-argument plumbing that feeds it are
 * therefore inert. Kept rather than removed: the three call sites pass
 * `Boolean(authToken)`, which documents *intent* ("this read is authenticated")
 * at the point of use, and deleting the flag would quietly change three
 * signatures for no behavioural gain. Recorded so nobody adds a fourth
 * believing it does something.
 */
export const getEventById = ({
  id,
  passToken,
}: {
  id: string;
  passToken?: boolean;
}): Promise<ApiResponse<EventDetailRecord>> =>
  apiClient.get(`/events/${id}/`, { params: passToken ? { pass_token: true } : {} }).then((r) => r.data);

/**
 * Answers with **`EventResource`, not `WebsiteEventResource`** — the admin
 * shape, which names the same collections differently (`images` /
 * `sponsor_images` rather than `event_images` / `event_sponsor_images`).
 *
 * Typed `AdminEventRecord`, which is that shape. It used to be `unknown`, with
 * the reasoning that claiming the website shape would be wrong and no caller
 * reads the body anyway — true as far as it goes, but `unknown` records the
 * ambiguity rather than resolving it. The admin resource is now modelled, so
 * the difference between the two is stated once and a caller reaching for
 * `event_images` on a created event gets a compile error naming `images`
 * instead of `undefined` at runtime.
 *
 * Note `images` and `sponsor_images` are optional on this type: `store()`
 * resolves the resource without eager loads, so a create response omits both.
 */
export const createEvent = (
  /* `FormData` — the poster and the gallery make every call multipart; see
     `updateEvent` below for why the verb is POST either way. */
  data: FormData
): Promise<ApiResponse<AdminEventRecord>> =>
  apiClient.post("/events/", data).then((r) => r.data);

/**
 * 201 with the new event — the same **admin-shaped** `EventResource` as
 * `createEvent`, and here `images` / `sponsor_images` *are* present, because
 * `republish()` resolves `fresh(['images', 'sponsorImages', 'interests'])`.
 * No caller reads it.
 */
export const republishEvent = ({
  id,
  formData,
}: {
  id: string;
  formData: FormData;
}): Promise<ApiResponse<AdminEventRecord>> =>
  apiClient.post(`/event/republish/${id}`, formData).then((r) => r.data);

// See `updateVolunteerOpportunity` — same PATCH+multipart workaround.
/* Same `EventResource` (admin-shaped) body as `createEvent`, with the two
   image collections present — `update()` resolves `$event->fresh()`. */
export const updateEvent = ({
  id,
  formData,
}: {
  id: string;
  formData: FormData;
}): Promise<ApiResponse<AdminEventRecord>> => {
  formData.append("_method", "PATCH");
  return apiClient.post(`/events/${id}/`, formData).then((r) => r.data);
};

/*
 * No close/reopen-registration wrapper: `POST /events/{id}/close-registration/`
 * answers 410 — events use external registration only.
 */

export const requestEventDeletion = (eventId: string, { requestOnly = false, reason }: {
  requestOnly?: boolean; reason?: string;
} = {}): Promise<ApiResponse<null>> =>
  apiClient.post(`/events/${eventId}/request-deletion/`, { request_only: requestOnly, reason }).then((r) => r.data);

/*
 * Events are an announcement surface only: the organizer runs sign-ups on their
 * own channel through the event's `registration_link`, so Fursa never holds a
 * participation or attendance record for one.
 *
 * The backend still exposes `/event-registrations/` (list, create, update with
 * `is_attended`, XLSX export), `/events/{id}/unregister/` and
 * `/event-time-slots/`, and those wrappers used to live here. They are gone on
 * purpose — do not add them back. See BE-41 in `FURSA_BACKEND_ISSUES.md` for the
 * matching backend removal.
 */

// ─── Event Feedbacks ─────────────────────────────────────────────────────────

/**
 * One event review, through `WebsiteEventFeedbackResource`.
 *
 * `likes_count` is counted in PHP from the loaded relation
 * (`is_liked == true && is_deleted == false`), so it is already a plain number
 * and never null.
 *
 * There is **no "is this mine" flag.** The screen used to read
 * `user_feedback`, which appears nowhere in the backend — the same phantom key
 * that made the *opportunity* reviews list show "write a review" to someone
 * who already had one. Here it was harmless only because the comparison beside
 * it (`user.id === viewer.id`) was doing the work; that comparison is now the
 * whole test. `user.id` is nullable on the resource (`$feedback->user?->id`),
 * which is why it is typed so.
 */
export interface EventFeedbackRecord {
  id: number;
  event_id: number;
  /** 1–5. */
  rating: number;
  comment_en: string | null;
  comment_ar: string | null;
  /** The enum's backing value, `"en"` or `"ar"`. */
  primary_language: string | null;
  likes_count: number;
  user: {
    id: number | null;
    full_name: string | null;
    nickname: string | null;
    profile_pic: string | null;
  };
  /** ISO 8601. */
  created_at: string | null;
}

/** Omitting `event_id` returns every event's reviews, unfiltered. */
export const getEventFeedbacks = (
  eventId?: string | number
): Promise<ApiResponse<EventFeedbackRecord[]>> =>
  apiClient
    .get("/event-feedback/", {
      params: eventId ? { event_id: eventId } : undefined,
    })
    .then((r) => r.data);

/**
 * `EventFeedbackController::store()` — which is an **upsert**.
 *
 * A second submit for the same event updates the existing review instead of
 * failing: the controller looks for one by `(user_id, event_id)` first, and
 * answers **201 when it created and 200 when it updated**. So a caller cannot
 * read "already reviewed" off the status.
 *
 * `rating` is `min:1, max:5`; both comments are `nullable`;
 * `primary_language` is `Rule::in(['en', 'ar'])`.
 *
 * Unlike the *opportunity* feedback controller, this one runs
 * `normalizeEventFeedbackPayload()` first, which accepts `event` as an alias
 * for `event_id` and a single `comment` resolved into the active locale's
 * column. That difference is why the same key mistake was harmless here and
 * broke review creation on learn-serve opportunities — `event_id` is sent
 * from here regardless, since the alias only applies when the canonical key
 * is absent.
 */
export interface CreateEventFeedbackBody {
  event_id: number;
  /** 1–5 inclusive. */
  rating: number;
  comment_en?: string | null;
  comment_ar?: string | null;
  primary_language?: "en" | "ar";
}

/**
 * `update()` takes no event id — a review cannot be moved between events —
 * and `rating` is `sometimes`.
 *
 * It also validates a bare `comment`, then `unset`s it before saving: the key
 * is accepted only so the normaliser can fold it into `comment_en` /
 * `comment_ar`. Not exposed here, because sending the pair directly is
 * unambiguous while `comment` depends on the request's locale.
 */
export type UpdateEventFeedbackBody = Partial<
  Omit<CreateEventFeedbackBody, "event_id">
>;

/** The created or updated review, in the same shape the list returns. */
export const createEventFeedback = (
  data: CreateEventFeedbackBody
): Promise<ApiResponse<EventFeedbackRecord>> =>
  apiClient.post("/event-feedback/", data).then((r) => r.data);

export const updateEventFeedback = ({
  feedback_id,
  data,
}: {
  feedback_id: string;
  data: UpdateEventFeedbackBody;
}): Promise<ApiResponse<EventFeedbackRecord>> =>
  apiClient.patch(`/event-feedback/${feedback_id}/`, data).then((r) => r.data);

export const deleteEventFeedback = (feedback_id: string): Promise<ApiResponse<null>> =>
  apiClient.delete(`/event-feedback/${feedback_id}/`).then((r) => r.data);

/**
 * `EventFeedbackLikeController::store()` — `updateOrCreate` keyed on
 * `(user_id, feedback_id)`, so it is also the *unlike*: send
 * `is_liked: false`. Always 201, even when it updated an existing row.
 *
 * The key is **`feedback`**, not `feedback_id`, and the response echoes the
 * ids under `user` / `feedback` rather than `user_id` / `feedback_id` — the
 * controller builds that array by hand rather than through a Resource.
 *
 * No current caller: the event detail screen likes a review through
 * `/event-feedback/{id}/like/`. Kept and typed because the endpoint exists
 * and is reachable; if it stays unused it should be deleted rather than left
 * untyped.
 */
export interface LikeEventFeedbackBody {
  feedback: number;
  /** Omitted means `true`. */
  is_liked?: boolean;
}

export interface EventFeedbackLikeRecord {
  id: number;
  /** The liking user's id — named `user`, not `user_id`. */
  user: number;
  /** The feedback's id — named `feedback`, not `feedback_id`. */
  feedback: number;
  is_liked: boolean;
  /** ISO 8601. */
  created_at: string | null;
  updated_at: string | null;
}

export const likeEventFeedback = (
  data: LikeEventFeedbackBody
): Promise<ApiResponse<EventFeedbackLikeRecord>> =>
  apiClient.post("/event-feedback-like/", data).then((r) => r.data);
