"use client";

import React from "react";

/**
 * Auth Context (RHL-020)
 *
 * Purpose:
 * - Provide a tiny, app-wide session state for the UI:
 *   - status: "unknown" | "loading" | "authenticated" | "unauthenticated" | "error"
 *   - user: { userId, role, branchId, email, mustChangePassword } | null
 *   - error: string | null
 *   - isValidating: boolean (true while a background session re-check runs)
 *   - retry: () => void | null (re-run the session check)
 */

/**
 * @typedef {"unknown"|"loading"|"authenticated"|"unauthenticated"|"error"} AuthStatus
 */

/**
 * @typedef {Object} AuthUser
 * @property {string} userId
 * @property {string} role
 * @property {string|null} branchId
 * @property {string|null} email
 * @property {boolean} mustChangePassword
 */

/**
 * @typedef {Object} AuthState
 * @property {AuthStatus} status
 * @property {AuthUser|null} user
 * @property {string|null} error
 * @property {boolean} isValidating
 * @property {(() => void)|null} retry
 */

/** @type {AuthState} */
export const DEFAULT_AUTH_STATE = Object.freeze({
	status: "unknown",
	user: null,
	error: null,
	isValidating: false,
	retry: null,
});

const AuthContext = React.createContext(DEFAULT_AUTH_STATE);

/**
 * Consume the auth context.
 *
 * @returns {AuthState}
 */
export function useAuth() {
	return React.useContext(AuthContext);
}

/**
 * Provider wrapper.
 *
 * @param {{ value: Partial<AuthState>, children: React.ReactNode }} props
 */
export function AuthProvider({ value, children }) {
	const merged = React.useMemo(() => {
		return { ...DEFAULT_AUTH_STATE, ...(value || {}) };
	}, [value]);

	return <AuthContext.Provider value={merged}>{children}</AuthContext.Provider>;
}
