export type GeolocationResult = {
    latitude: number;
    longitude: number;
};

export function useGeolocation() {
    function getCurrentPosition(): Promise<GeolocationResult> {
        return new Promise((resolve, reject) => {
            if (!navigator.geolocation) {
                reject(new Error('Perangkat tidak mendukung geolokasi.'));

                return;
            }

            navigator.geolocation.getCurrentPosition(
                (position) => {
                    resolve({
                        latitude: position.coords.latitude,
                        longitude: position.coords.longitude,
                    });
                },
                (error) => {
                    const messages: Record<number, string> = {
                        1: 'Izin lokasi ditolak. Aktifkan izin lokasi untuk presensi.',
                        2: 'Lokasi tidak tersedia. Coba lagi.',
                        3: 'Waktu permintaan lokasi habis. Coba lagi.',
                    };

                    reject(new Error(messages[error.code] ?? 'Gagal mendapatkan lokasi.'));
                },
                {
                    enableHighAccuracy: true,
                    timeout: 15000,
                    maximumAge: 0,
                },
            );
        });
    }

    return {
        getCurrentPosition,
    };
}
