File size: 2,012 Bytes
345b8ff
 
 
0122657
 
 
 
 
 
 
345b8ff
 
 
 
0122657
 
 
345b8ff
 
 
 
 
 
 
0122657
345b8ff
 
 
 
0122657
 
 
 
345b8ff
 
 
 
 
 
 
 
 
 
 
 
 
0122657
 
 
 
 
345b8ff
0122657
 
 
345b8ff
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"use client";

import { createContext, useContext, useState, useEffect, ReactNode } from "react";
import {
  DEFAULT_TENANT_ID,
  TENANT_STORAGE_KEY,
  DEFAULT_USER_ROLE,
  ROLE_STORAGE_KEY,
  USER_ROLES,
} from "@/lib/constants";

type TenantContextType = {
  tenantId: string;
  setTenantId: (id: string) => void;
  role: (typeof USER_ROLES)[number];
  setRole: (role: (typeof USER_ROLES)[number]) => void;
  availableRoles: typeof USER_ROLES;
  isLoading: boolean;
};

const TenantContext = createContext<TenantContextType | undefined>(undefined);

export function TenantProvider({ children }: { children: ReactNode }) {
  const [tenantId, setTenantIdState] = useState("");
  const [role, setRoleState] = useState<(typeof USER_ROLES)[number]>(DEFAULT_USER_ROLE);
  const [isLoading, setIsLoading] = useState(true);

  // Load from localStorage on mount
  useEffect(() => {
    const savedTenant = localStorage.getItem(TENANT_STORAGE_KEY);
    const savedRole = localStorage.getItem(ROLE_STORAGE_KEY) as (typeof USER_ROLES)[number] | null;
    setTenantIdState(savedTenant || DEFAULT_TENANT_ID);
    setRoleState(savedRole && USER_ROLES.includes(savedRole) ? savedRole : DEFAULT_USER_ROLE);
    setIsLoading(false);
  }, []);

  const setTenantId = (id: string) => {
    const trimmed = id.trim();
    setTenantIdState(trimmed);
    if (trimmed) {
      localStorage.setItem(TENANT_STORAGE_KEY, trimmed);
    } else {
      localStorage.removeItem(TENANT_STORAGE_KEY);
    }
  };

  const setRole = (newRole: (typeof USER_ROLES)[number]) => {
    setRoleState(newRole);
    localStorage.setItem(ROLE_STORAGE_KEY, newRole);
  };

  return (
    <TenantContext.Provider
      value={{ tenantId, setTenantId, role, setRole, availableRoles: USER_ROLES, isLoading }}
    >
      {children}
    </TenantContext.Provider>
  );
}

export function useTenant() {
  const context = useContext(TenantContext);
  if (!context) {
    throw new Error("useTenant must be used within TenantProvider");
  }
  return context;
}