import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export async function GET(request: Request) {
    try {
        const currentUser = await getCurrentUser();
        if (!currentUser || currentUser.role !== 'admin') {
            return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        const templates = await prisma.adminEmailTemplate.findMany({
            orderBy: { updated_at: 'desc' }
        });

        return NextResponse.json({ data: templates });
    } catch (error: any) {
        console.error("Error fetching admin templates:", error);
        return NextResponse.json({ error: "Internal server error" }, { status: 500 });
    }
}

export async function POST(request: Request) {
    try {
        const currentUser = await getCurrentUser();
        if (!currentUser || currentUser.role !== 'admin') {
            return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        const body = await request.json();
        const { type, subject, html_body, is_active } = body;

        if (!type || !subject || !html_body) {
            return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
        }

        const template = await prisma.adminEmailTemplate.upsert({
            where: { type },
            update: { subject, html_body, is_active },
            create: { type, name: type, subject, html_body, is_active }
        });

        return NextResponse.json({ success: true, data: template });
    } catch (error: any) {
        console.error("Error saving admin template:", error);
        return NextResponse.json({ error: "Internal server error" }, { status: 500 });
    }
}
