import apiClient from "@/lib/api/client";
import type { ApiResponse } from "@/lib/api/types";
import type { LearnServeRegistrationRecord } from "@/features/opportunities/permissionRecord";
import type { VolunteerAttendanceRecord } from "@/features/opportunities/services/attendance";

/**
 * Approved attendance contracts (BE-191/192), to be enforced independently server-side.
 * Volunteering uses the same daily IN/OUT QR with start-1h/end+2h bounds.
 * Development uses one presence scan from the final scheduled day's session
 * start until midnight, with advance printing independent of scan activation.
 * The raw QR payload is rendered/decoded by the website, never fabricated here.
 * Legacy Laravel timing restrictions remain backend work, not a client bypass.
 */

// ─── Volunteering: one printed presence code ─────────────────────────────────

/** Stable volunteering QR. Expired sheets remain available for reference. */
export interface VolunteerAttendanceCode {
  code: string;
  expires_at: string | null;
  is_expired: boolean;
}

/**
 * Creator-only. Idempotent: the server generates the code once and returns the
 * same string on every later call.
 */
export const getVolunteerAttendanceCode = (
  id: string
): Promise<ApiResponse<VolunteerAttendanceCode>> =>
  apiClient.get(`/volunteer-opportunities/${id}/attendance-qr/`).then((r) => r.data);

/** BE-191: the server records daily arrival/departure and credited actual minutes. */
export const volunteerSelfScan = (payload: {
  code: string;
  /** BE-101 — sent only when the opportunity requires an on-site scan. */
  latitude?: number;
  longitude?: number;
  accuracy?: number;
}): Promise<ApiResponse<VolunteerAttendanceRecord>> =>
  apiClient.post("/volunteer-attendance/self-scan/", payload).then((r) => r.data);

// ─── Learn & serve: one code, one scan for the whole course ──────────────────

export interface LearnServeAttendanceCode {
  code: string;
  expires_at: string;
  /** BE-192: true for a printable sheet whose scanning window has expired. */
  is_expired?: boolean;
  /** BE-192: actual final-session start, without a one-hour lead. */
  scan_opens_at?: string | null;
  scan_closes_at?: string | null;
}

/**
 * BE-192: creator-only, stable code printable before start and after completion.
 * Printing must never activate scanning or extend/rotate an already printed code.
 * The old server's 24-hour print limit is explicitly removed by the backend task.
 */
export const issueLearnServeAttendanceCode = (
  id: string
): Promise<ApiResponse<LearnServeAttendanceCode>> =>
  apiClient.post(`/learn-serve-opportunities/${id}/attendance-qr/`).then((r) => r.data);

/**
 * BE-192: one presence scan, at/after the actual start on the only/final day.
 * The server enforces enrollment, opening/closing instants and duplicate protection.
 * Returns the participant's refreshed registration row.
 */
export const learnServeSelfScan = (payload: {
  code: string;
}): Promise<ApiResponse<LearnServeRegistrationRecord>> =>
  apiClient.post("/learn-serve-attendance/self-scan/", payload).then((r) => r.data);

/**
 * Live eligible scan rows. Server timestamps share each scan endpoint's rules:
 * volunteering start-1h/end+2h; development only/final session start to midnight.
 * The navbar consumes these authoritative instants, not a second inferred window.
 */
export interface MyAttendanceScanRecord {
  opportunity_id: number;
  opportunity_type: "volunteer_opportunity" | "learn_serve_opportunity";
  title_en: string | null;
  title_ar: string | null;
  scan_opens_at: string;
  scan_closes_at: string;
  /** Volunteering only — BE-101. */
  requires_attendance_location?: boolean;
  next_action?: "check_in" | "check_out" | "attend";
}

export const getMyAttendanceScans = (): Promise<ApiResponse<MyAttendanceScanRecord[]>> =>
  apiClient.get("/my-attendance-scans/").then((r) => r.data);

/**
 * A self-scan the server refused because attendance is already in — a second
 * completed volunteering arrival/departure pair, or any second development scan. A 409 on
 * both endpoints; the server's own message says which, so callers show it
 * verbatim. Re-scanning cannot change the answer, so the camera closes.
 */
export function isAttendanceAlreadyRecordedError(error: unknown): boolean {
  if (!error || typeof error !== "object") return false;
  const { response } = error as {
    response?: { status?: number; data?: { code?: number } };
  };
  return response?.status === 409 || response?.data?.code === 409;
}
