/**
 * Organization Role Hook
 *
 * Manages organization member role and permissions for multi-staff dashboard.
 * Fetches role from session and provides role-based access control utilities.
 *
 * @module components/dashboard/hooks/useOrganizationRole
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import {
  OrgRole,
  hasTabAccess,
  getPermissionsForRole,
  StaffPermissions,
  OWNER_ALLOWED_TABS,
  ADMIN_ALLOWED_TABS,
  STAFF_ALLOWED_TABS,
} from "@/lib/types/organization.types";

export interface UseOrganizationRoleReturn {
  role: OrgRole | null;
  organizationId: string | null;
  isOwner: boolean;
  isAdmin: boolean;
  isStaff: boolean;
  canAccessTab: (tab: string) => boolean;
  allowedTabs: string[];
  permissions: StaffPermissions;
  isLoading: boolean;
  error: string | null;
  refetch: () => Promise<void>;
}

/**
 * Hook to fetch and manage organization role for current user
 */
export function useOrganizationRole(): UseOrganizationRoleReturn {
  const [role, setRole] = useState<OrgRole | null>(null);
  const [organizationId, setOrganizationId] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchOrganizationRole = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);

      const response = await fetch("/api/organization/role", {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      });

      if (!response.ok) {
        if (response.status === 401 || response.status === 404) {
          // Unauthenticated or user is not part of an organization.
          // Solo owners continue with full access in the dashboard shell.
          setRole(null);
          setOrganizationId(null);
        } else {
          throw new Error("Failed to fetch organization role");
        }
      } else {
        const data = await response.json();
        setRole(data.role || null);
        setOrganizationId(data.organizationId || null);
      }
    } catch (err) {
      console.error("Error fetching organization role:", err);
      setError(err instanceof Error ? err.message : "Unknown error");
      setRole(null);
      setOrganizationId(null);
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchOrganizationRole();
  }, [fetchOrganizationRole]);

  // Derived values
  const isOwner = role === "OWNER";
  const isAdmin = role === "ADMIN";
  const isStaff = role === "STAFF";

  // If no organization (null role), user is a solo owner with full access
  const allowedTabs = role ? getAllowedTabsForRole(role) : OWNER_ALLOWED_TABS;

  const canAccessTab = useCallback(
    (tab: string) => {
      // Solo owners (no organization) have full access
      if (!role && !organizationId) {
        return true;
      }

      // Organization members use role-based access
      if (role) {
        return hasTabAccess(role, tab);
      }

      return false;
    },
    [role, organizationId],
  );

  const permissions = role
    ? getPermissionsForRole(role)
    : getPermissionsForRole("OWNER");

  return {
    role,
    organizationId,
    isOwner,
    isAdmin,
    isStaff,
    canAccessTab,
    allowedTabs,
    permissions,
    isLoading,
    error,
    refetch: fetchOrganizationRole,
  };
}

/**
 * Helper function to get allowed tabs for a role
 */
function getAllowedTabsForRole(role: OrgRole): string[] {
  switch (role) {
    case "OWNER":
      return OWNER_ALLOWED_TABS;
    case "ADMIN":
      return ADMIN_ALLOWED_TABS;
    case "STAFF":
      return STAFF_ALLOWED_TABS;
    default:
      return [];
  }
}
