'use client';

import { useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';

import { apiFetch } from '@/lib/api/client';
import { usePermissionsStore } from '@/stores/permissions-store';
import type { RolePermissions } from '@/lib/db/schema/users';

interface MeResponse {
  data: {
    userId: string;
    portId: string;
    portSlug: string;
    permissions: RolePermissions | null;
    isSuperAdmin: boolean;
    user: { email: string; name: string };
  };
}

export function PermissionsProvider({ children }: { children: React.ReactNode }) {
  const setPermissions = usePermissionsStore((s) => s.setPermissions);

  const { data } = useQuery<MeResponse>({
    queryKey: ['me'],
    queryFn: () => apiFetch<MeResponse>('/api/v1/me'),
    staleTime: 5 * 60 * 1000, // 5 minutes
    retry: 1,
  });

  useEffect(() => {
    if (data?.data) {
      setPermissions(data.data.permissions, data.data.isSuperAdmin, data.data.userId);
    }
  }, [data, setPermissions]);

  return <>{children}</>;
}
