import { NextRequest, NextResponse } from 'next/server';
import { workos, clientId } from '@/lib/workos';
import { setSession } from '@/lib/session';

export async function POST(request: NextRequest) {
    try {
        const body = await request.json() as {
            email?: string;
            password?: string;
            firstName?: string;
            lastName?: string;
            type?: 'signup' | 'login';
            stayLoggedIn?: boolean;
        };
        const { email, password, firstName, lastName, type, stayLoggedIn } = body;

        if (!email || !password) {
            return NextResponse.json({ error: 'Email and password are required' }, { status: 400 });
        }

        let user;

        // Handle Signup
        if (type === 'signup') {
            try {
                await workos.userManagement.createUser({
                    email,
                    password,
                    firstName,
                    lastName,
                    emailVerified: false, // WorkOS sends verification email automatically if configured
                });
            } catch (error: any) {
                // Handle user already exists
                if (error.code === 'user_already_exists') {
                    return NextResponse.json({ error: 'A user with this email already exists.' }, { status: 409 });
                }
                throw error;
            }
        }

        // Authenticate (for both login and after signup)
        try {
            const response = await workos.userManagement.authenticateWithPassword({
                email,
                password,
                clientId,
            });

            user = response.user;

            // extensive logging to debug structure if needed
            // console.log('Auth response:', JSON.stringify(response, null, 2));

            // Create session
            await setSession({
                user: {
                    id: user.id,
                    email: user.email,
                    firstName: user.firstName,
                    lastName: user.lastName,
                    profilePictureUrl: user.profilePictureUrl,
                },
                accessToken: response.accessToken, // Note: SDK returns camelCase
                refreshToken: response.refreshToken,
                stayLoggedIn: !!stayLoggedIn,
            });

            return NextResponse.json({ success: true, user });

        } catch (error: any) {
            console.error('Authentication error:', error);

            // Map WorkOS errors to user-friendly messages
            if (error.code === 'invalid_credentials' || error.message?.includes('Invalid credentials')) {
                return NextResponse.json({ error: 'Invalid email or password.' }, { status: 401 });
            }

            return NextResponse.json({ error: error.message || 'Authentication failed' }, { status: 400 });
        }

    } catch (error: any) {
        console.error('Login API error:', error);
        return NextResponse.json({ error: 'An internal error occurred.' }, { status: 500 });
    }
}
