// src/app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { NextAuthOptions } from "next-auth";

// Define auth options separately
const authOptions: NextAuthOptions = {
    providers: [
        // OAuth Provider for WHMCS
        {
            id: "whmcs",
            name: "WHMCS",
            type: "oauth",
            authorization: {
                url: `${process.env.BACKEND_URL}/api/v1/auth/whmcs/redirect`,
                params: { scope: "openid profile email" }
            },
            token: `${process.env.BACKEND_URL}/api/v1/auth/whmcs/callback`,
            userinfo: `${process.env.BACKEND_URL}/api/v1/auth/check-sessionv2`,
            clientId: process.env.WHMCS_CLIENT_ID,
            clientSecret: process.env.WHMCS_CLIENT_SECRET,
            profile(profile) {
                console.log('WHMCS profile response:', profile);
                return {
                    id: profile.user?.id.toString() || profile.id?.toString(),
                    name: profile.user?.name || profile.name,
                    email: profile.user?.email || profile.email,
                    whmcsId: profile.user?.whmcs_id || profile.whmcs_id,
                };
            },
        },

        // Credentials Provider for direct login
        CredentialsProvider({
            name: "WHMCS Credentials",
            credentials: {
                email: { label: "Email", type: "email" },
                password: { label: "Password", type: "password" }
            },
            async authorize(credentials) {
                try {
                    const res = await fetch(`${process.env.BACKEND_URL}/api/v1/auth/whmcs/login`, {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({
                            email: credentials?.email,
                            password: credentials?.password,
                        }),
                    });
                    console.log("email: ", credentials?.email);
                    console.log("password: ", credentials?.password);
                    console.log("res: ", res);
                    const data = await res.json();
                    console.log("data: ", data);
                    if (data.success) {
                        return {
                            id: data.user.id.toString(),
                            name: data.user.name,
                            email: data.user.email,
                            token: data.token,
                            whmcsId: data.user.whmcs_id,
                        };
                    }

                    throw new Error(data.message || "Authentication failed");
                } catch (error) {
                    console.error("Auth error:", error);
                    return null;
                }
            },
        }),
        CredentialsProvider({
            id: "token",
            name: "Token",
            credentials: {
                token: { label: "Token", type: "text" }
            },
            async authorize(credentials) {
                try {
                    if (!credentials?.token) return null;
                    
                    const res = await fetch(`${process.env.BACKEND_URL}/api/v1/auth/check-sessionv2`, {
                        method: "GET",
                        headers: { 
                            "Authorization": `Bearer ${credentials.token}`,
                            "Content-Type": "application/json" 
                        },
                    });
                    
                    const data = await res.json();
                    
                    if (data.authenticated) {
                        return {
                            id: data.user.id.toString(),
                            name: data.user.name,
                            email: data.user.email,
                            token: credentials.token,
                            whmcsId: data.user.whmcs_id,
                        };
                    }
                    
                    return null;
                } catch (error) {
                    console.error("Auth error:", error);
                    return null;
                }
            },
        }),
    ],

    callbacks: {
        async jwt({ token, user, account }) {
            console.log("jwt token: ", token);
            console.log("jwt user: ", user);
            console.log("jwt account: ", account);
            // Initial sign in
            if (account && user) {
                return {
                    ...token,
                    accessToken: user.token || account.access_token,
                    userId: user.id,
                    whmcsId: user.whmcsId,
                };
            }

            // Return previous token if the access token has not expired yet
            return token;
        },

        async session({ session, token }) {
            session.user.id = token.userId;
            session.user.whmcsId = token.whmcsId;
            session.accessToken = token.accessToken;
            console.log("session token: ", token);
            console.log("session session: ", session);
            return session;
        },
        async redirect({ url, baseUrl }) {
            // This is crucial for proper redirection handling
            // If the URL starts with the base URL, return it as is
            console.log("redirect url: ", url);
            if (url.startsWith(baseUrl)) return url;
            // Otherwise, make sure we're redirecting to the base URL
            console.log("redirect baseUrl: ", baseUrl);
            return baseUrl;
        }
    },

    pages: {
        signIn: '/auth/signin',
        signOut: '/auth/signout',
        error: '/auth/error',
        verifyRequest: '/auth/verify-request',
    },

    session: {
        strategy: "jwt",
        maxAge: 30 * 24 * 60 * 60, // 30 days
    },

    debug: process.env.NODE_ENV === "development",
};

// Create the handler using the auth options
const handler = NextAuth(authOptions);

// Export the handler as GET and POST - these are the only valid exports for route handlers
export { handler as GET, handler as POST };
