import NextAuth, { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import bcrypt from 'bcryptjs';
import pool from '../../../../lib/db';
import { NextRequest } from 'next/server';

// ---- Auto-create users table and seed admin on first boot ----
async function ensureUsersTable() {
    await pool.execute(`
        CREATE TABLE IF NOT EXISTS users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            email VARCHAR(255) UNIQUE NOT NULL,
            password_hash VARCHAR(255) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    `);

    // Seed admin if not already present
    const [rows] = await pool.execute<any[]>(
        'SELECT id FROM users WHERE email = ?',
        ['admin@devtrixx.com']
    );
    if (rows.length === 0) {
        const hash = await bcrypt.hash('Admin@12345@#', 14); // cost=14 for strong hashing
        await pool.execute(
            'INSERT INTO users (email, password_hash) VALUES (?, ?)',
            ['admin@devtrixx.com', hash]
        );
    }
}

// Run once on server boot (non-blocking — any error is logged, not thrown)
ensureUsersTable().catch(err => console.error('[Auth] DB init error:', err));

// ---- NextAuth Configuration ----
const authOptions: NextAuthOptions = {
    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;

                // Normalise email (lowercase, trim)
                const email = credentials.email.trim().toLowerCase();

                try {
                    const [rows] = await pool.execute<any[]>(
                        'SELECT id, email, password_hash FROM users WHERE email = ?',
                        [email]
                    );

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

                    const user = rows[0];
                    const valid = await bcrypt.compare(credentials.password, user.password_hash);
                    if (!valid) return null;

                    return { id: String(user.id), email: user.email };
                } catch (err) {
                    console.error('[Auth] authorize error:', err);
                    return null;
                }
            },
        }),
    ],

    session: {
        strategy: 'jwt',
        maxAge: 8 * 60 * 60, // 8 hours
    },

    jwt: {
        maxAge: 8 * 60 * 60,
    },

    pages: {
        signIn: '/login',
        error: '/login',
    },

    callbacks: {
        async jwt({ token, user }) {
            if (user) {
                token.id = user.id;
                token.email = user.email;
            }
            return token;
        },
        async session({ session, token }) {
            if (token && session.user) {
                (session.user as any).id = token.id;
            }
            return session;
        },
    },

    // Never reveal whether email or password was wrong — always "Invalid credentials"
    debug: false,
};

const handler = NextAuth(authOptions);

export async function GET(req: NextRequest, ctx: any) {
    return (handler as any)(req, ctx);
}

export async function POST(req: NextRequest, ctx: any) {
    return (handler as any)(req, ctx);
}
