import { NextResponse } from 'next/server';
import { auth, clerkClient } from '@clerk/nextjs/server';
import { connectDB } from '@/lib/mongodb';
import User from '@/models/User';

export async function GET() {
    try {
        const { userId } = await auth();

        if (!userId) {
            return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
        }

        await connectDB();

        // 1. Update MongoDB
        const user = await User.findOneAndUpdate(
            { clerkId: userId },
            { role: 'super_admin' },
            { new: true } // Return updated doc
        );

        if (!user) {
            return NextResponse.json({ error: 'User not found in DB' }, { status: 404 });
        }

        // 2. Update Clerk Metadata (CRITICAL for Sync)
        try {
            const client = await clerkClient();
            await client.users.updateUserMetadata(userId, {
                publicMetadata: {
                    role: 'super_admin',
                },
            });
        } catch (clerkError) {
            console.error('Failed to update Clerk metadata:', clerkError);
            return NextResponse.json({
                success: false,
                error: 'DB updated but Clerk Sync failed. Check Secret Key.'
            }, { status: 500 });
        }

        return NextResponse.json({
            success: true,
            message: 'You are now Super Admin in BOTH DB and Clerk!',
            user
        });

    } catch (error) {
        return NextResponse.json(
            { error: 'Internal server error: ' + (error instanceof Error ? error.message : 'Unknown error') },
            { status: 500 }
        );
    }
}
