import { AccessLevel } from '@/shared/api/file-manager';
import { permissionApi } from '@/shared/api/permission';
import { getUserByEmail } from '@/shared/api/user';
import { PermissionUpdateRequest } from '@/shared/types/permission';
import { IUser } from '@/shared/types/user';
import { useState, useEffect } from 'react';


export const usePermissions = (documentId: number) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [canRead, setCanRead] = useState(false);
  const [canWrite, setCanWrite] = useState(false);
  const [userData, setUserData] = useState<IUser | null>(null);

  useEffect(() => {
    const fetchUserAndPermissions = async () => {
      const userEmail = localStorage.getItem('email');
      if (!userEmail || !documentId) return;

      try {
        setLoading(true);
        // Récupérer les données utilisateur
        const user = await getUserByEmail(userEmail);
        setUserData(user);

        // Vérifier les permissions
        const [readPermission, writePermission] = await Promise.all([
          permissionApi.checkPermission(Number(documentId), Number(user.id), AccessLevel.READ),
          permissionApi.checkPermission(Number(documentId), Number(user.id), AccessLevel.WRITE)
        ]);

        setCanRead(readPermission);
        setCanWrite(writePermission);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Error checking permissions');
      } finally {
        setLoading(false);
      }
    };

    fetchUserAndPermissions();
  }, [documentId]);

  return {
    loading,
    error,
    canRead,
    canWrite,
    userData,
    checkPermission: async (level: AccessLevel) => 
      userData?.id ? permissionApi.checkPermission(Number(documentId), Number(userData.id), level) : false,
    updatePermission: async (request: PermissionUpdateRequest) => 
      permissionApi.updatePermission(Number(documentId), request),
    revokePermission: async (userId: number) => 
      permissionApi.revokePermission(Number(documentId), Number(userId)),
  };
};