import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma";
import { z } from "zod/v4";
import { NotificationType } from "@/prisma/generated/prisma";

const schema = z.object({
    name: z.string(),
    type: z.string(),
    config: z.string(),
})

export async function POST(request: NextRequest) {
    try {
    const body = await request.json();
    const { name, type, config } = schema.parse(body);

    if(type !== "TELEGRAM") {
        return NextResponse.json({ error: "Invalid notification type" }, { status: 400 });
    }

    const parsedConfig = JSON.parse(config);
    if(parsedConfig.token === "" || parsedConfig.chat_id === "") {
        return NextResponse.json({ error: "Invalid config" }, { status: 400 });
    }

    const notification = await prisma.notificationProvider.create({
        data: { name, type: type as NotificationType, config: parsedConfig},
    });

    return NextResponse.json({ notification }, { status: 201 });
    } catch (error) {
        if(error instanceof z.ZodError) {
            return NextResponse.json({ error: error.issues[0].message }, { status: 400 });
        }
        return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
    }
}