import { router } from '@inertiajs/vue3';

export const ONLINE_AUCTION_GRID_PREFILL_KEY = 'online_auction_grid_prefill';
export const IN_PERSON_AUCTION_GRID_PREFILL_KEY = 'in_person_auction_grid_prefill';

export interface AuctionGridPrefill {
    userId: number;
    category?: string;
}

export function navigateToOnlineAuctionGrid(userId: number, category?: string): void {
    const prefill: AuctionGridPrefill = { userId };

    if (category) {
        prefill.category = category;
    }

    sessionStorage.setItem(ONLINE_AUCTION_GRID_PREFILL_KEY, JSON.stringify(prefill));
    router.visit(route('admin.online-auctions.index'));
}

export function navigateToInPersonAuctionGrid(userId: number, category?: string): void {
    const prefill: AuctionGridPrefill = { userId };

    if (category) {
        prefill.category = category;
    }

    sessionStorage.setItem(IN_PERSON_AUCTION_GRID_PREFILL_KEY, JSON.stringify(prefill));
    router.visit(route('admin.in-person-auctions.index'));
}

export function readAuctionGridPrefill(storageKey: string): AuctionGridPrefill | null {
    if (typeof window === 'undefined') {
        return null;
    }

    const stored = sessionStorage.getItem(storageKey);

    if (!stored) {
        return null;
    }

    sessionStorage.removeItem(storageKey);

    try {
        const parsed = JSON.parse(stored) as AuctionGridPrefill;

        if (typeof parsed.userId !== 'number' || parsed.userId <= 0) {
            return null;
        }

        return parsed;
    } catch {
        return null;
    }
}
