import { useMemo } from "react"

import api from "@shared/api"

interface UseVideoMetadataResult {
	aspectRatio: number
	isLoading: boolean
	isError: boolean
}

const DEFAULT_ASPECT_RATIO = 16 / 9

export function useVideoMetadata(
	fileId: string | null,
): UseVideoMetadataResult {
	const {
		data: mediaFile,
		isLoading,
		isError,
	} = api.useQuery(
		"get",
		"/api/media/mediafiles/{media_file_id}/",
		{
			params: {
				path: {
					media_file_id: fileId ?? "",
				},
			},
		},
		{
			enabled: !!fileId,
			retry: false,
		},
	)

	const aspectRatio = useMemo(() => {
		if (!mediaFile?.width || !mediaFile?.height) {
			return DEFAULT_ASPECT_RATIO
		}
		return mediaFile.width / mediaFile.height
	}, [mediaFile])

	return {
		aspectRatio,
		isLoading,
		isError,
	}
}
