import { toast } from 'sonner';
import { RareItemApiResponse } from '../types';

/**
 * Get CSRF token from meta tag
 */
function getCsrfToken(): string {
    return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
}

/**
 * Load rare item configuration from server
 * @param path - Path to the rare_item.conf file
 * @returns Promise with the file content
 */
export async function loadRareItem(path: string): Promise<string> {
    try {
        const response = await fetch('/admin/fitur/load-rare-item', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': getCsrfToken()
            },
            body: JSON.stringify({ path })
        });

        const data: RareItemApiResponse = await response.json();

        if (data.success && data.content) {
            return data.content;
        } else {
            toast.error(data.message || 'Failed to load rare_item.conf');
            throw new Error(data.message || 'Failed to load file');
        }
    } catch (error) {
        console.error('Error loading rare items:', error);
        toast.error('Error loading rare_item.conf file');
        throw error;
    }
}

/**
 * Save rare item configuration to server
 * @param path - Path to the rare_item.conf file
 * @param content - Content to save
 */
export async function saveRareItem(path: string, content: string): Promise<void> {
    try {
        const response = await fetch('/admin/fitur/save-rare-item', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': getCsrfToken()
            },
            body: JSON.stringify({ path, content })
        });

        const data: RareItemApiResponse = await response.json();

        if (data.success) {
            toast.success('rare_item.conf saved successfully!');
        } else {
            toast.error(data.message || 'Failed to save file');
            throw new Error(data.message || 'Failed to save file');
        }
    } catch (error) {
        console.error('Error saving rare items:', error);
        toast.error('Error saving rare_item.conf file');
        throw error;
    }
}
