import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import db from '@/lib/db';
import crypto from 'crypto';

const handler = NextAuth({
    providers: [
        CredentialsProvider({
            name: 'Credentials',
            credentials: {
                email: { label: 'Email', type: 'email' },
                password: { label: 'Password', type: 'password' },
            },
            async authorize(credentials) {
                if (!credentials?.email || !credentials?.password) return null;

                const hashedPassword = crypto
                    .createHash('md5')
                    .update(credentials.password)
                    .digest('hex');

                const [rows]: any = await db.query(
                    'SELECT * FROM users WHERE email = ? AND password = ?',
                    [credentials.email, hashedPassword]
                );

                if (rows.length === 0) return null;

                const user = rows[0];
                return {
                    id: user.id,
                    name: user.name,
                    email: user.email,
                    role: user.role,
                };
            },
        }),
    ],
    callbacks: {
        async jwt({ token, user }) {
            if (user) token.role = (user as any).role;
            return token;
        },
        async session({ session, token }) {
            if (session.user) (session.user as any).role = token.role;
            return session;
        },
    },
    pages: {
        signIn: '/my-account',
    },
    secret: process.env.NEXTAUTH_SECRET,
});

export { handler as GET, handler as POST };