import { translate } from '@/composables/useI18n';

/** A failed JSON request: `errors` follows Laravel's validation shape (field → messages). */
export class HttpError extends Error {
    constructor(
        message: string,
        public readonly status: number,
        public readonly errors: Record<string, string[]> = {},
    ) {
        super(message);
    }

    /** field → first message, ready for `form.setError()`. */
    firstErrors(): Record<string, string> {
        return Object.fromEntries(
            Object.entries(this.errors).map(([field, messages]) => [field, messages[0] ?? '']),
        );
    }
}

function xsrfToken(): string | null {
    const match = document.cookie.match(/(?:^|;\s*)XSRF-TOKEN=([^;]+)/);

    return match ? decodeURIComponent(match[1]) : null;
}

/**
 * Same-origin JSON request with Laravel's CSRF header. Rejects with HttpError on non-2xx
 * (validation and domain errors carry translated messages) or on network failure.
 */
export async function requestJson<T>(
    method: 'get' | 'post' | 'put' | 'patch' | 'delete',
    url: string,
    body?: Record<string, unknown>,
): Promise<T> {
    const headers: Record<string, string> = {
        Accept: 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
    };
    const token = xsrfToken();

    if (token) {
        headers['X-XSRF-TOKEN'] = token;
    }

    if (body && method !== 'get') {
        headers['Content-Type'] = 'application/json';
    }

    let response: Response;

    try {
        response = await fetch(url, {
            method: method.toUpperCase(),
            headers,
            credentials: 'same-origin',
            body: body && method !== 'get' ? JSON.stringify(body) : undefined,
        });
    } catch {
        throw new HttpError(translate('shows.errors.network'), 0);
    }

    const data = await response.json().catch(() => null);

    if (!response.ok) {
        throw new HttpError(
            (data && typeof data.message === 'string' && data.message) ||
                translate('shows.errors.generic'),
            response.status,
            (data && data.errors) || {},
        );
    }

    return data as T;
}
