Files
NaMesa_site/reserva-mesa-dashboard/hooks/useStaff.ts

77 lines
1.9 KiB
TypeScript

"use client";
import { useState, useEffect } from "react";
import { ref, onValue, off, update, push, remove } from "firebase/database";
import { db } from "@/lib/firebase";
import { useAuth } from "@/hooks/useAuth";
import { Staff } from "@/types/staff";
export function useStaff() {
const { user } = useAuth();
const [staff, setStaff] = useState<Staff[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (!user?.email) return;
const staffRef = ref(db, "Staff");
const unsubscribe = onValue(staffRef, (snapshot) => {
const data = snapshot.val();
const list: Staff[] = [];
if (data) {
Object.keys(data).forEach((key) => {
const item = data[key];
if (item.restauranteEmail === user.email) {
list.push({
id: key,
...item
});
}
});
}
setStaff(list);
setLoading(false);
});
return () => off(staffRef, "value", unsubscribe);
}, [user?.email]);
const addStaff = async (member: Omit<Staff, "id" | "restauranteEmail">) => {
if (!user?.email) return { success: false, error: "Utilizador não autenticado" };
try {
const newStaffRef = push(ref(db, "Staff"));
const staffData: Staff = {
id: newStaffRef.key as string,
...member,
restauranteEmail: user.email
};
await update(newStaffRef, staffData);
return { success: true };
} catch (error) {
console.error("Erro ao adicionar funcionário:", error);
return { success: false, error };
}
};
const deleteStaff = async (staffId: string) => {
try {
await remove(ref(db, `Staff/${staffId}`));
return { success: true };
} catch (error) {
console.error("Erro ao remover funcionário:", error);
return { success: false, error };
}
};
return {
staff,
loading,
addStaff,
deleteStaff
};
}