
import NextAuth, { DefaultSession, User } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';



declare module 'next-auth' {
    interface Session {
        user: User;
    }

    export interface User {
        id: string; // Ensure this property is included
        success: boolean,
        message: string
        accessToken: string,
        userInfo:
        {
            id: string,
            fullName: string,
            role: string,
            password: string
            country: string
            mobile: string
            username: string
            status: string
            photo: string
            clinet_token: string
            hashRt: string
        },
        sessionID: string

    }
    interface JWT {
        user: User & DefaultSession['user'];
    }
}
const maxAge = Number(process.env.maxAge) || 60 * 60 * 24;
const handler = NextAuth({
    session: {
        strategy: 'jwt',
        maxAge,
    },
    secret: process.env.SECRET || ",secret",
    pages: {
        signIn: '/signIn',
    },
    debug: true,
    logger: {
        error(code, metadata) {
            console.error(code, metadata);
        },
        debug(code, metadata) {
            console.debug(code, metadata);
        },
        warn(code) {
            console.warn(code);
        },
    },
    callbacks: {
        jwt: async ({ token, user, trigger, session }) => {
            if (user) {
                token.user = user;
            }
            if (trigger === 'update') {
                token.user = session.info;
            }
            return token;
        },

        session: async ({ session, token }) => {
            session.user = token.user as User;
            return { ...session };
        },
    },
    providers: [
        CredentialsProvider({
            credentials: {
                username: {},
                password: {},
            },
            async authorize(credentials: any): Promise<User | null> {
                try {
                    const { password, username } = credentials;

                    if (!password || !username) {
                        throw new Error('No credentials provided');
                    }

                    const response = await fetch(`${process.env.BASIC_URL}user/login
                    `, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ password, username }),
                        credentials: 'include',
                    });

                    if (response.status !== 200) {
                        throw new Error('Login Failed');
                    }
                    const data = (await response.json()) as User;
                    if (!data) {
                        throw new Error('Login Failed');
                    }
                    if (!data.success) {
                        throw new Error(JSON.stringify(data));
                    }
                    if (data.userInfo.role != 'admin') {
                        throw new Error(JSON.stringify(data));
                    }
                    return data;
                } catch (error) {
                    console.log(error);
                    throw Error(`${error}`);
                }
            },
        }),
    ],
});

export { handler as GET, handler as POST };
