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 redemptions = await db.redemption.findMany({
            where: {
                userId: user.id
            }
        })

        return NextResponse.json(redemptions.map(({userId, ...attrs}) => attrs));
    } 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 { actionName, redemptionId, order, state }: { actionName: string, redemptionId: string, order: number, state: boolean } = await req.json();
        if (!redemptionId && !actionName && !order)
            return NextResponse.json({ message: 'One of the following fields must exist: redemptionId, actionName, order, state.', error: null, value: null }, { status: 400 })

        if (actionName && actionName.length > 32)
            return NextResponse.json({ message: 'actionName cannot be longer than 32 characters.', error: null, value: null }, { status: 400 })

        const action = await db.action.findFirst({
            where: {
                name: actionName
            }
        })
        if (!action)
            return NextResponse.json({ message: 'Action does not exist.', error: null, value: null }, { status: 400 })

        let data:any = {
            actionName,
            order,
            state
        }

        if (!data.actionName)
            data = { actionName, ...data }
        if (!data.order)
            data = { order, ...data }
        if (!data.state)
            data = { state, ...data }

        const res = await db.redemption.create({
            data: {
                userId: user.id,
                redemptionId,
                order,
                state: true,
                ...data
            }
        });

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

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

        const { id, actionName, redemptionId, order, state }: { id: string, actionName: string, redemptionId: string, order: number, state: boolean } = await req.json();
        if (!redemptionId && !actionName && !order)
            return NextResponse.json({ message: 'One of the following fields must exist: redemptionId, actionName, order, state.', error: null, value: null }, { status: 400 })

        if (actionName && actionName.length > 32)
            return NextResponse.json({ message: 'actionName cannot be longer than 32 characters.', error: null, value: null }, { status: 400 })

        const action = await db.action.findFirst({
            where: {
                name: actionName
            }
        })
        if (!action)
            return NextResponse.json({ message: 'Action does not exist.', error: null, value: null }, { status: 400 })

        let data:any = {
            actionName,
            redemptionId,
            order,
            state
        }

        if (!data.actionName)
            data = { actionName, ...data }
        if (!data.order)
            data = { order, ...data }
        if (!data.state)
            data = { state, ...data }
        if (!data.redemptionId)
            data = { redemptionId, ...data }

        const res = await db.redemption.update({
            where: {
                id
            },
            data: data
        });

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

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

        const { searchParams } = new URL(req.url)
        const id = searchParams.get('id') as string
        const redemptions = await db.redemption.delete({
            where: {
                id
            }
        })

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