import { component$, Slot, useSignal } from "@builder.io/qwik";
import { type DocumentHead, RequestHandler, routeLoader$ } from "@builder.io/qwik-city";
import Header from "~/components/layout/Header";
import { AddFriends } from "~/components/features/AddFriends";
import axios from "axios";
import { useContextProvider } from "@builder.io/qwik";
import { AppStateContext } from "~/utils/context";
export const onRequest: RequestHandler = async ({ cookie, sharedMap, redirect , params}) => {
    const token = cookie.get("access_token")?.value; 
    console.log(token + "이것은 유저페이지로 들어온 token");
    if (!token) {
        console.log("no token");
        throw redirect(302, "/auth");
    }
    try {
        // jwt.verify(token, process.env.JWT_SECRET!);
        const userInfo = await axios.get(`http://localhost:8000/api/user/profile/${params.username}`, {
            headers: {
                Authorization: `Bearer ${token}`,
            },
        });
        console.log("data : " +     userInfo.data);
        console.log("token verified");
        
        const res = await axios.get('http://localhost:8000/api/user/me', {
            headers: {
                Authorization: `Bearer ${token}`,
            },
        });
        sharedMap.set("user", res.data);
            
    } catch (e : any) {
        if(e.response.status === 404) {
            console.log("user not found");
            throw redirect(302, "/");
        }
        else {
            console.log("token not verified");
            cookie.delete("access_token");
            throw redirect(302, "/auth");
        }
    }
};
export const useUser = routeLoader$(({sharedMap}) => {
    return sharedMap.get("user");
});
export default component$(() => {   
    const addFriends = useSignal<boolean>(false);
    const userData = useUser();
    useContextProvider(AppStateContext, userData.value);
    return (
        <div class="flex min-h-screen">
            <Header showAddFriends={addFriends}  />
            {addFriends.value == true ? <AddFriends showAddFriends={addFriends} /> : null}
            <main class="flex-1 min-h-screen">
                <Slot />
            </main>
        </div>
    );
});

export const head: DocumentHead = {
    title: "2025 AnA SSF Pages",
    meta: [
        {
            name: "description",
            content: "2025 AnA SSF Pages with Qwik",
        },
    ],
};
