"use server";

import {Account, Client, Databases, Messaging, Users} from "node-appwrite";
import {cookies} from "next/headers";
import {ADMIN_DASHBOARD_URL, CLIENTS_DASHBOARD_URL, PATIENT_DASHBOARD_URL, SESSION_KEY} from "@/lib/constants";
import {UserType} from "@/lib/backend/appwrite_types";
import {redirect} from "next/navigation";
import {useAuth} from "@/lib/hooks/useAuth";

export async function createSessionClient() {
    const client = new Client()
        .setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT!)
        .setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT!);

    const session = cookies().get(SESSION_KEY);
    if (!session || !session.value) {
        throw new Error("No session");
    }

    client.setSession(session.value);

    return {
        client,
        get account() {
            return new Account(client);
        },
        get databases() {
            return new Databases(client)
        },
    };
}


export async function createAdminClient() {
    const client = new Client()
        .setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT!)
        .setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT!)
        .setKey(process.env.NEXT_APPWRITE_KEY!);

    return {
        client,
        get messaging() {
            return new Messaging(client)
        },
        get users() {
            return new Users(client)
        },
        get databases() {
            return new Databases(client)
        },
        get account() {
            return new Account(client);
        },
    };
}


export async function redirectToDashboardUser() {
    const {userProfile} = await useAuth();
    if (userProfile) {
        switch (userProfile.userType) {
            case UserType.ADMIN:
                redirect(ADMIN_DASHBOARD_URL)
                return;
            case UserType.PATIENT:
                redirect(PATIENT_DASHBOARD_URL)
                return;
            default:
                redirect(CLIENTS_DASHBOARD_URL)
        }

    }
}