import { certificateDownloadFilename } from "@/lib/certificateDownloadFilename";
import type { PublicProfileResponse } from "@/features/profile/components/commonProfileTypes";
import type { VolunteerQrCode } from "@/features/opportunities/permissionRecord";
import type {
  AccountRecord,
  VolunteerProfileRecord,
} from "@/features/profile/accountRecords";
import type { OrganizerProfileRecord } from "@/features/profile/components/organizerAccountRecords";
import type {
  AllProfilesPayload,
  OrganizationDirectoryItem,
  VolunteerDirectoryItem,
} from "@/features/profile/profileDirectoryRecord";
import apiClient from "@/lib/api/client";
import type { ApiResponse } from "@/lib/api/types";
import type { ProfilesListParams } from "@/features/profile/components/MoreProfile";

// ─── Account ─────────────────────────────────────────────────────────────────

export const getAccountInfo = (): Promise<ApiResponse<AccountRecord>> =>
  apiClient.get("/account/").then((r) => r.data);

// POST, not PATCH — PHP only populates $_FILES for POST bodies, so a PATCH
// carrying a multipart profile picture upload silently drops the file server-side.
export const updateAccountInfo = (
  formData: FormData
): Promise<ApiResponse<AccountRecord>> =>
  apiClient.post("/account/", formData).then((r) => r.data);

// ─── Volunteer / Organizer profiles ──────────────────────────────────────────

export const getVolunteerProfile = (): Promise<
  ApiResponse<VolunteerProfileRecord>
> => apiClient.get("/volunteer-profile/").then((r) => r.data);

/**
 * `VolunteerProfileUpdateRequest` — every key `nullable`, so a partial save is
 * the normal case and this is a wholly optional shape.
 *
 * Four things the rules say that the field names do not:
 *
 *  - the stored column is **`experience`**, not `experience_field` — the form
 *    value is called the latter and has to be mapped;
 *  - `health_concerns` is `in:yes,no`, a two-value string and not a boolean;
 *  - `gender` and `emergency_contact_relationship` are master-choice **ids**,
 *    `exists:master_choices,id`;
 *  - `civil_id` / `passport_number` are not validated for presence here. Which
 *    one is required depends on nationality and residency, and
 *    `IdentityDocumentValidator` decides — *and only when the request actually
 *    touched identity*, because `prepareForValidation()` back-fills the
 *    omitted one from the stored record first (BE-50 / BE-56). So a save that
 *    leaves them out is not an attempt to clear them.
 *
 * `website_link` is accepted here but **not** by the organization endpoint.
 * All link fields are validated `url`, so a bare domain is a 422.
 */
export interface UpdateVolunteerProfileBody {
  first_name?: string;
  last_name?: string;
  /** `max:50`. */
  nickname?: string;
  /** `max:100`. */
  occupation?: string;
  /** The `experience` column; the form calls this field `experience_field`. */
  experience?: string;
  /** `in:yes,no` — not a boolean. */
  health_concerns?: "yes" | "no";
  is_public?: boolean;
  is_verified?: boolean;
  show_real_name?: boolean;
  /** A master-choice id. */
  gender?: number | string;
  /** `max:12`; see the note above on when it is required. */
  civil_id?: string;
  /** `max:20`. */
  passport_number?: string;
  email?: string;
  /** One of `Nationality::personValues()`. */
  nationality?: string;
  /** One of `ResidencyStatus::values()`. */
  residency_status?: string;
  /** BE-77 — only asked of non-Kuwaitis. */
  speaks_arabic?: boolean;
  /** `Y-m-d`; an omitted or blank value preserves the stored date. */
  dob?: string | null;
  birth_year?: number;
  instagram_link?: string;
  whatsapp_link?: string;
  linkedin_link?: string;
  facebook_link?: string;
  website_link?: string;
  twitter_link?: string;
  receive_reminder_emails?: boolean;
  do_not_disturb?: boolean;
  /** `max:15`. */
  phone_number?: string;
  /** `max:5`. */
  country_code?: string;
  emergency_contact_name?: string;
  emergency_contact_phone?: string;
  emergency_contact_country_code?: string;
  emergency_contact_civil_id?: string;
  /** A master-choice id. */
  emergency_contact_relationship?: number | string;
  interest_ids?: (number | string)[];
}

/**
 * The updated profile, in the same shape `GET /volunteer-profile/` returns.
 *
 * One refusal is worth knowing about because it is not a field error the form
 * can prevent: an **approved trainer** sending `show_real_name: false` gets a
 * 422 with that field named — "Approved trainers must show their real name."
 */
export const updateVolunteerProfile = (
  data: UpdateVolunteerProfileBody
): Promise<ApiResponse<VolunteerProfileRecord>> =>
  apiClient.patch("/volunteer-profile/", data).then((r) => r.data);

export const getOrganizerProfile = (): Promise<
  ApiResponse<OrganizerProfileRecord>
> => apiClient.get("/organization-profile/").then((r) => r.data);

/**
 * `OrganizationProfileController::update()` — again wholly optional.
 *
 * Differences from the volunteer body that are easy to assume away:
 *
 *  - there is **no `website_link`** here. The volunteer rules accept one; this
 *    validator does not list it, and the organizer form does not send one.
 *  - `organizer_type` is a master-choice id constrained to the `org_type`
 *    choice type — an id from any other list is a 422 rather than a
 *    wrong-but-accepted value. There is no `sector` (cancelled, PDF p.9).
 *  - the bank fields exist for the paid-opportunity payout and are what
 *    `requires_bank_details_for_paid_opportunities` on the read side refers to.
 *
 * **Changing `organizer_type` sends the account back for review**: the
 * controller sets `organization_status = PENDING` whenever the submitted id
 * differs from the stored one, which withdraws publishing until an admin
 * approves it again. Nothing in the payload signals that; it is a consequence
 * of the field.
 */
export interface UpdateOrganizerProfileBody {
  /** `max:50`. */
  nickname?: string;
  /** `max:255`. */
  company_name?: string;
  /** A master-choice id from the `org_type` list — see the note above. */
  organizer_type?: number | string;
  /** `max:100`. */
  registration_number?: string;
  /** `max:100`. */
  license_number?: string;
  internal_license_document?: File;
  internal_license_document_removed?: boolean;
  latitude?: number | string;
  longitude?: number | string;
  /** `max:100`. */
  bank_id?: number;
  bank_name?: string;
  /** `max:150`. */
  bank_account_holder_name?: string;
  /** `max:50`. */
  bank_account_number?: string;
  /** One of `Nationality::personValues()`. */
  nationality?: string;
  instagram_link?: string;
  whatsapp_link?: string;
  linkedin_link?: string;
  facebook_link?: string;
  twitter_link?: string;
  interest_ids?: (number | string)[];
}

export const updateOrganizerProfile = (
  data: UpdateOrganizerProfileBody
): Promise<ApiResponse<OrganizerProfileRecord>> => {
    if (!data.internal_license_document) {
      return apiClient.patch("/organization-profile/", data).then((r) => r.data);
    }
    const form = new FormData();
    form.append("_method", "PATCH");
    for (const [key, value] of Object.entries(data)) {
      if (value === undefined) continue;
      if (Array.isArray(value)) {
        if (value.length) value.forEach((item) => form.append(`${key}[]`, String(item)));
        else form.append(key, "");
      } else {
        form.append(key, value instanceof Blob ? value : typeof value === "boolean" ? (value ? "1" : "0") : String(value));
      }
    }
    return apiClient.post("/organization-profile/", form).then((r) => r.data);
};

/** One stored licence document, through `OrganizationDocumentResource`. */
export interface OrganizationDocumentRecord {
  id: number;
  /** `getimg()` — absolute URL, or null when the row has no file. */
  document: string | null;
  /** ISO 8601. */
  uploaded_at: string | null;
}

/**
 * The reply is the organization's **whole remaining document set**, not just
 * the ones added — the controller returns a collection, so the caller can
 * replace its list rather than merge into it.
 */
export const updateOrganizerDocuments = (
  formData: FormData
): Promise<ApiResponse<OrganizationDocumentRecord[]>> => {
  // Method spoofing keeps the HTTP contract as PUT while letting PHP receive
  // multipart files through a POST body.
  formData.append("_method", "PUT");
  return apiClient
    .post("/organization-profile/documents/", formData)
    .then((r) => r.data);
};

export const getQRCode = (): Promise<ApiResponse<VolunteerQrCode>> =>
  apiClient.get("/volunteer-profile/qr-code/").then((r) => r.data);

/* The same endpoint as `getQRCode` — an organizer's code is issued from the
   volunteer-profile route too. Kept as a separate name because the two call
   sites read it for different screens. */
export const getOrganizerQRCode = (): Promise<ApiResponse<VolunteerQrCode>> =>
  apiClient.get("/volunteer-profile/qr-code/").then((r) => r.data);

// ─── Public profiles directory ───────────────────────────────────────────────

export const getPublicProfile = (
  id: string
): Promise<ApiResponse<PublicProfileResponse>> =>
  apiClient.get(`/public-profile/${id}/`).then((r) => r.data);

// Combined 3-bucket preview (`data.volunteer` / `data.organization` /
// `data.volunteer_team`, each capped at `limit`) — for the profiles
// directory overview only. For a single bucket's full paginated list use
// the dedicated `getVolunteerProfilesList` / `getOrganizationProfilesList` /
// `getVolunteerTeamProfilesList` below instead.
/* `ProfilesListParams` rather than the generic `QueryParams`: these three
   endpoints have a known, closed parameter list and a typed response, both
   already declared next to the screen that uses them. */
export const getAllProfiles = (
  params?: ProfilesListParams
): Promise<ApiResponse<AllProfilesPayload>> =>
  apiClient.get("/all-profiles/", { params }).then((r) => r.data);

/** Full paginated volunteer list — flat `data` array + top-level `meta.pagination`. */
export const getVolunteerProfilesList = (
  params?: ProfilesListParams
): Promise<ApiResponse<VolunteerDirectoryItem[]>> =>
  apiClient.get("/profiles/volunteers/", { params }).then((r) => r.data);

/** Full paginated organization list — excludes volunteer-team-type organizers. */
export const getOrganizationProfilesList = (
  params?: ProfilesListParams
): Promise<ApiResponse<OrganizationDirectoryItem[]>> =>
  apiClient.get("/profiles/organizations/", { params }).then((r) => r.data);

/**
 * Full paginated volunteer-team list.
 *
 * Note the row type: a volunteer team is an `organization_profiles` row and
 * the controller serializes it with the resource's **`organization`** branch,
 * so these rows carry `first_name`/`last_name` and a hard-coded
 * `is_public: true` — not the volunteer shape.
 */
export const getVolunteerTeamProfilesList = (
  params?: ProfilesListParams
): Promise<ApiResponse<OrganizationDirectoryItem[]>> =>
  apiClient.get("/profiles/volunteer-teams/", { params }).then((r) => r.data);

// ─── Certificates ────────────────────────────────────────────────────────────

/**
 * `certificateType` narrows the list to one type, and is the choice's English
 * value verbatim (`Volunteer`, `Course`, `Internship` — see the
 * `certificate_filter_type` choices). Omit it for "All".
 *
 * The filtering belongs on this endpoint rather than in the client: the same
 * list is paged on screen, so narrowing it after the fact would page a list the
 * server never agreed to. An unrecognised value is a **422** naming the field
 * (BE-53), not a silently unfiltered list.
 *
 * `user_id` is accepted and **ignored**: BE-46 made the endpoint always read
 * the caller's own profile, because it used to trust the parameter and let
 * anyone enumerate another volunteer's certificates. The argument is kept
 * because every call site passes it and it is the React Query key; it has no
 * effect on what comes back.
 */
/** One row of `/user-certificates/`, built by hand in the controller. */
export interface UserCertificateRecord {
  /**
   * The registration's id — and it needs `registration_type` beside it to be
   * usable: the two registration tables have independent id sequences, so the
   * id alone is ambiguous when passed to `/download-certificate/`.
   */
  registration_id: number;
  registration_type: "volunteer" | "learn_serve";
  /** `volunteering` | `course` | `internship`. */
  certificate_kind: "volunteering" | "course" | "internship";
  /** `getimg()` — null when the row is certified but has no stored file. */
  certificate_image: string | null;
  opportunity__title_en: string | null;
  opportunity__title_ar: string | null;
  organizer_name: string | null;
}

/**
 * The counts this endpoint reports beside `data`.
 *
 * Deliberately **not** `CountedApiResponse`: that one's keys are
 * `all / volunteer / development`, which is what the opportunity *list*
 * endpoints send. This one sends `all / volunteer / course / internship` —
 * `development` is split into its two learning types here and does not exist
 * as a key.
 */
export interface UserCertificateCounts {
  all: number;
  volunteer: number;
  course: number;
  internship: number;
}

export const getUserCertificates = (
  userId: string | number,
  certificateType?: string
): Promise<
  ApiResponse<UserCertificateRecord[]> & { counts?: UserCertificateCounts }
> =>
  apiClient
    .get("/user-certificates/", {
      params: {
        user_id: userId,
        ...(certificateType ? { certificate_type: certificateType } : {}),
      },
    })
    .then((r) => r.data);

/**
 * Download the generated certificate attached to a registration.
 *
 * `registration_type` is optional but worth passing whenever the caller knows
 * it: the learn-serve and volunteer registration tables have independent id
 * sequences, so an id can exist in both. Without the param the backend tries
 * learn-serve first and falls back to volunteer, which silently returns the
 * wrong document on a collision (BE-14).
 */
export const downloadUserCertificate = ({
  registration_id,
  registration_type,
  fallbackName = "certificate",
}: {
  registration_id: string | number;
  registration_type?: "volunteer" | "learn_serve";
  fallbackName?: string;
}) =>
  apiClient
    .get("/download-certificate/", {
      params: registration_type
        ? { registration_id, registration_type }
        : { registration_id },
      responseType: "blob",
    })
    .then((response) => {
      const disposition = response.headers["content-disposition"] as
        | string
        | undefined;
      return {
        blob: response.data as Blob,
        filename: certificateDownloadFilename(disposition, response.headers["content-type"] || response.data.type, fallbackName),
      };
    });
