import { db } from "@/lib/db"
import { NextResponse } from "next/server";
import fetchUserWithImpersonation from '@/lib/fetch-user-impersonation';


export async function GET(req: Request) {
    try {
        const user = await fetchUserWithImpersonation(req);
        if (!user) {
            return NextResponse.json({ error: null, message: "Unauthorized", success: false }, { status: 401 });
        }

        const data = await db.connection.findMany({
            where: {
                userId: user.id,
                default: true
            }
        })

        return NextResponse.json({ error: null, message: null, success: true, data }, { status: 200 });
    } catch (error: any) {
        return NextResponse.json({ error, message: "Failed to get default connection", success: false }, { status: 500 });
    }
}

export async function PUT(req: Request) {
    try {
        const user = await fetchUserWithImpersonation(req);
        if (!user) {
            return NextResponse.json({ error: null, message: "Unauthorized", success: false }, { status: 401 });
        }

        const { name } = await req.json();
        if (!name)
            return NextResponse.json({ error: null, message: 'Requires "name" param to be passed in - name of the connection.', success: false }, { status: 400 })

        const connection = await db.connection.findFirst({
            where: {
                userId: user.id,
                name
            }
        })

        if (!connection) {
            return NextResponse.json({ error: null, message: 'Connection with that name does not exist.', success: false }, { status: 400 })
        }

        await db.connection.updateMany({
            where: {
                userId: user.id,
                type: connection.type,
                default: true
            },
            data: {
                default: false
            }
        })

        const data = await db.connection.update({
            where: {
                userId_name: {
                    userId: user.id,
                    name,
                }
            },
            data: {
                default: true as boolean
            }
        })

        return NextResponse.json({ error: null, message: null, success: true, data }, { status: 200 });
    } catch (error: any) {
        return NextResponse.json({ error, message: "Failed to update default connection", success: false }, { status: 500 });
    }
}