import { NextResponse, type NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { getStaffSession } from "@/lib/staff-session";

export async function GET() {
  const campaigns = await prisma.campaigns.findMany({
    orderBy: { createdAt: "desc" },
  });

  return NextResponse.json({ data: campaigns });
}

export async function POST(request: NextRequest) {
  const user = await getStaffSession();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await request.json();
  const {
    name,
    utmSource,
    utmMedium,
    utmCampaign,
    utmContent,
    landingPage,
    kpis,
  } = body;

  if (!name) {
    return NextResponse.json({ error: "name is required" }, { status: 400 });
  }

  const record = await prisma.campaigns.create({
    data: {
      name,
      utmSource,
      utmMedium,
      utmCampaign,
      utmContent,
      landingPage,
      kpis: kpis ?? null,
      createdBy: user.id,
    },
  });

  return NextResponse.json({ data: record });
}
