import apiClient from "@/lib/api/client";
import type { ApiResponse } from "@/lib/api/types";
import type { PermissionListRow } from "@/features/opportunities/permissionRecord";
import type { VolunteerPickerRecord } from "@/features/opportunities/rolesAndTeamsRecord";

export const getAllVolunteers = (params?: {
  page?: number;
  limit?: number;
  search?: string;
  opportunity_id?: string | number;
  event_id?: string | number;
}): Promise<ApiResponse<VolunteerPickerRecord[]>> =>
  apiClient.get("/all-volunteers/", { params }).then((r) => r.data);

// ─── Attendance permission — «إذن تحضير» (BE-69) ─────────────────────────────

/**
 * A separate grant from `/scan-permissions/`, and deliberately so: that one
 * delegated **QR scanning** and is retired (the backend answers 410). This one lets a
 * volunteer add other volunteers to the opportunity and record their hours,
 * which is what the client asked for — «إذن يعطى لمتطوع لاضافه متطوعين في
 * الفرصه وتحديد عدد ساعات التطوع وليس التحضير باستخدام الـ QR».
 *
 * Volunteer opportunities only; there is no event equivalent.
 */
export const getAttendancePermissionsList = (params: {
  opportunity_id: string | number;
  search?: string;
  page?: number;
  limit?: number;
}): Promise<ApiResponse<PermissionListRow[]>> =>
  apiClient.get("/attendance-permissions/list/", { params }).then((r) => r.data);

/**
 * One entry per requested user, in request order. The backend `updateOrCreate`s
 * on (user_id, opportunity_id), so repeating a call updates the same row and
 * `attendance_permission_id` stays stable. Revoking is the same call with
 * `is_allowed: false` — there is no delete route.
 */
export interface AttendancePermissionBulkUpdateEntry {
  user_id: number;
  /** The persisted value — trust this over what was sent. */
  is_allowed: boolean;
  attendance_permission_id: number;
}

export const bulkUpdateAttendancePermissions = (data: {
  opportunity_id: string | number;
  user_ids: number[];
  is_allowed: boolean;
}): Promise<ApiResponse<AttendancePermissionBulkUpdateEntry[]>> =>
  apiClient
    .post("/attendance-permissions/bulk-update/", data)
    .then((r) => r.data);

// ─── Attendance (QR scan + manual) ───────────────────────────────────────────

/**
 * One attendance record, through `VolunteerAttendanceResource`.
 *
 * One presence scan per day (16 Oct client confirmation): `checked_in_at` is
 * when the attendance was recorded, by scan or by hand. The resource still
 * emits a deprecated `checked_out_at`, always null for new records, which is
 * deliberately not typed here so nothing starts reading it again.
 */
export interface VolunteerAttendanceRecord {
  id: number;
  registration_id: number;
  /** `Y-m-d`. */
  attended_date: string | null;
  /**
   * The credited hours, as a JSON **number**.
   *
   * Not an `ArabicNumeric`: `VolunteerOpportunityAttendance` casts the column
   * to `float`, and this resource does not pass it through `ar_num()` — only
   * the four `Website/*` resources do that, which is where the
   * digits-as-strings problem lives. So arithmetic on this is safe.
   */
  total_hours: number | null;
  is_attended: boolean;
  /** `AttendanceService::VIA_*` — how it was recorded (`scan` / `manual` / …). */
  recorded_via: string | null;
  /** ISO 8601. */
  checked_in_at: string | null;
  checked_out_at?: string | null;
  total_minutes?: number;
  /** ISO 8601; set once the organizer corrected the hours (BE-91). */
  hours_set_manually_at?: string | null;
  /** `first_name last_name`, trimmed. */
  volunteer_name: string | null;
  opportunity_id: number | null;
  opportunity_title_en: string | null;
  opportunity_title_ar: string | null;
}

/**
 * Marks a registered volunteer present without a QR scan. Volunteers check
 * themselves in by scanning the opportunity code; this is the fallback. `total_hours` is optional; omitting it makes
 * the backend derive the hours from the opportunity's duration.
 *
 * The volunteer is identified by any one of `user_id` / `registration_id` /
 * `volunteer_uuid`.
 */
export const markManualVolunteerAttendance = (data: {
  opportunity_id: string | number;
  user_id?: string | number;
  registration_id?: string | number;
  volunteer_uuid?: string;
  attendance_date?: string;
  total_hours?: number;
}): Promise<ApiResponse<VolunteerAttendanceRecord>> =>
  apiClient.post("/volunteer-attendance/manual/", data).then((r) => r.data);

/** Corrects the logged hours on an attendance record — manual or QR alike. */
export const updateVolunteerAttendanceHours = ({
  attendance_id,
  total_hours,
}: {
  attendance_id: string | number;
  /** `min:0`, `max:24`, and additionally capped at the session's own maximum —
      over that is a 422 naming the maximum, not a silent clamp. */
  total_hours: number;
}): Promise<ApiResponse<VolunteerAttendanceRecord>> =>
  apiClient
    .patch(`/volunteer-attendance/${attendance_id}/hours/`, { total_hours, total_minutes: Math.round(total_hours * 60) })
    .then((r) => r.data);

/**
 * Reverses a check-in and returns the hours to the volunteer's balance. The
 * same volunteer can then be checked in again for the same day with corrected
 * hours — that re-check-in is the point of the endpoint.
 */
export const undoVolunteerAttendance = (
  attendance_id: string | number
): Promise<ApiResponse<null>> =>
  apiClient
    .post(`/volunteer-attendance/${attendance_id}/undo/`)
    .then((r) => r.data);

/** The window's new bounds, as `reopenWindow()` reports them. */
export interface ReopenedCheckInWindow {
  id: number;
  /** ISO 8601 — the explicit extension that was just stored. */
  preparation_reopened_until: string;
  /** ISO 8601, or null when the opportunity sets no window at all. */
  preparation_valid_until: string | null;
  is_preparation_window_closed: boolean;
}

/**
 * Admin-only: reopens a closed check-in window, either by extending it
 * `extra_hours` past its current end or by naming an explicit `reopen_until`
 * timestamp. Non-admins get a 403.
 */
export const reopenOpportunityCheckIn = ({
  opportunity_id,
  extra_hours,
  reopen_until,
}: {
  opportunity_id: string | number;
  extra_hours?: number;
  reopen_until?: string;
}): Promise<ApiResponse<ReopenedCheckInWindow>> =>
  apiClient
    .post(
      `/admin/volunteer-opportunities/${opportunity_id}/reopen-check-in/`,
      reopen_until ? { reopen_until } : { extra_hours }
    )
    .then((r) => r.data);
