/**
 * Typed access to the plugin's REST API (/wp-json/brickmoat/v1). WordPress's apiFetch adds
 * the nonce and the site's REST root. The shapes come from @brickmoat/shared.
 */
import apiFetch from '@wordpress/api-fetch';
import { useCallback, useEffect, useRef, useState } from 'react';
import { mockRequest, mockEnabled } from './mock';

const NAMESPACE = '/brickmoat/v1';

export class ApiFailure extends Error {
	code: string;
	status: number;
	constructor( message: string, code = 'unknown', status = 0 ) {
		super( message );
		this.code = code;
		this.status = status;
	}
}

type Query = Record< string, string | number | boolean | null | undefined >;

function withQuery( path: string, query?: Query ): string {
	if ( ! query ) {
		return path;
	}
	const params = new URLSearchParams();
	for ( const [ key, value ] of Object.entries( query ) ) {
		if ( value !== undefined && value !== null && value !== '' ) {
			params.set( key, String( value ) );
		}
	}
	const text = params.toString();
	return text ? `${ path }?${ text }` : path;
}

async function request< T >( method: 'GET' | 'POST' | 'DELETE', path: string, options: { query?: Query; data?: unknown } = {} ): Promise< T > {
	if ( mockEnabled() ) {
		return mockRequest< T >( method, path, options );
	}
	try {
		return await apiFetch< T >( {
			path: withQuery( NAMESPACE + path, options.query ),
			method,
			...( options.data !== undefined ? { data: options.data } : {} ),
		} );
	} catch ( error ) {
		const failure = error as { message?: string; code?: string; data?: { status?: number } };
		throw new ApiFailure( failure?.message || 'Request failed.', failure?.code, failure?.data?.status );
	}
}

export const api = {
	get: < T >( path: string, query?: Query ) => request< T >( 'GET', path, { query } ),
	post: < T >( path: string, data?: unknown ) => request< T >( 'POST', path, { data: data ?? {} } ),
	delete: < T >( path: string ) => request< T >( 'DELETE', path ),
};

export interface Loaded< T > {
	data: T | null;
	error: ApiFailure | null;
	/** True on the first load only; refreshes keep showing the data they already have. */
	loading: boolean;
	refreshing: boolean;
	reload: () => void;
	/** Replace the data with an answer you already have (for example from a POST). */
	set: ( data: T ) => void;
}

/**
 * Loads a GET route and keeps it fresh.
 * `pollMs` re-reads it on a timer while the tab is visible.
 */
export function useLoad< T >( path: string | null, query?: Query, pollMs?: number ): Loaded< T > {
	const [ data, setData ] = useState< T | null >( null );
	const [ error, setError ] = useState< ApiFailure | null >( null );
	const [ loading, setLoading ] = useState( path !== null );
	const [ refreshing, setRefreshing ] = useState( false );
	const [ tick, setTick ] = useState( 0 );
	const key = path === null ? null : withQuery( path, query );
	const latest = useRef( 0 );

	const shownKey = useRef< string | null >( null );

	useEffect( () => {
		if ( key === null ) {
			shownKey.current = null;
			setData( null );
			setLoading( false );
			return;
		}
		// A different route starts from a loading state; a refresh keeps what is on screen.
		if ( shownKey.current !== key ) {
			shownKey.current = key;
			setData( null );
			setError( null );
			setLoading( true );
		}
		const mine = ++latest.current;
		setRefreshing( true );
		request< T >( 'GET', key )
			.then( ( answer ) => {
				if ( mine === latest.current ) {
					setData( answer );
					setError( null );
				}
			} )
			.catch( ( failure: ApiFailure ) => {
				if ( mine === latest.current ) {
					setError( failure );
				}
			} )
			.finally( () => {
				if ( mine === latest.current ) {
					setLoading( false );
					setRefreshing( false );
				}
			} );
	}, [ key, tick ] );

	const reload = useCallback( () => setTick( ( value ) => value + 1 ), [] );

	useEffect( () => {
		if ( ! pollMs || key === null ) {
			return;
		}
		const timer = window.setInterval( () => {
			if ( document.visibilityState === 'visible' ) {
				reload();
			}
		}, pollMs );
		return () => window.clearInterval( timer );
	}, [ pollMs, key, reload ] );

	const set = useCallback( ( next: T ) => {
		latest.current++;
		setData( next );
		setError( null );
		setLoading( false );
		setRefreshing( false );
	}, [] );

	return { data, error, loading, refreshing, reload, set };
}
