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({ message: 'Unauthorized.', error: null, value: null }, { status: 401 });
        }

        const voiceStates = await db.ttsVoiceState.findMany({
            where: {
                userId: user.id
            }
        });

        const voiceNames = await db.ttsVoice.findMany();
        const voiceNamesMapped: { [id: string]: string } = Object.assign({}, ...voiceNames.map(v => ({ [v.id]: v.name })))

        return NextResponse.json(voiceStates.filter(v => v.state).map(v => voiceNamesMapped[v.ttsVoiceId]));
    } catch (error) {
        return NextResponse.json({ message: 'Something went wrong', error: error, value: null }, { status: 500 })
    }
}

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

        const { voice, state }: { voice: string, state: boolean } = await req.json();

        const voiceIds = await db.ttsVoice.findMany();
        const voiceIdsMapped: { [voice: string]: string } = Object.assign({}, ...voiceIds.map(v => ({ [v.name.toLowerCase()]: v.id })));
        if (!voiceIdsMapped[voice.toLowerCase()]) {
            return NextResponse.json({ message: 'Voice does not exist.', error: null, value: null }, { status: 400 });
        }

        await db.ttsVoiceState.upsert({
            where: {
                userId_ttsVoiceId: {
                    userId: user.id,
                    ttsVoiceId: voiceIdsMapped[voice.toLowerCase()]
                }
            },
            update: {
                state
            },
            create: {
                userId: user.id,
                ttsVoiceId: voiceIdsMapped[voice.toLowerCase()],
                state
            }
        });

        return NextResponse.json({ message: null, error: null, value: null }, { status: 200 })
    } catch (error) {
        return NextResponse.json({ message: 'Something went wrong', error: error, value: null }, { status: 500 })
    }
}