import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { logMemory } from "@/lib/services/client-memory";
import {
  listBriefs,
  getBrief,
  createBrief,
  updateBrief,
  deleteBrief,
  BriefType,
  BriefStatus,
} from "@/lib/services/content-briefs";

/**
 * GET /api/content-briefs?brandId=xxx&type=seo&status=draft
 * GET /api/content-briefs?id=xxx  (single brief)
 */
export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);

  // Single brief by ID
  const briefId = searchParams.get("id");
  if (briefId) {
    const brief = await getBrief(briefId);
    if (!brief) return NextResponse.json({ error: "Not found" }, { status: 404 });
    return NextResponse.json(brief);
  }

  // List by brand
  const brandId = searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId is required" }, { status: 400 });

  // Verify access
  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  if (!brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const briefs = await listBriefs(brandId, {
    type: searchParams.get("type") as BriefType | undefined,
    status: searchParams.get("status") as BriefStatus | undefined,
  });

  return NextResponse.json(briefs);
}

/**
 * POST /api/content-briefs
 * action: "create" | "update" | "delete"
 */
export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  try {
    const body = await req.json();

    // ── CREATE ──
    if (body.action === "create") {
      const { brandId, type, title } = body;
      if (!brandId || !type || !title) {
        return NextResponse.json({ error: "brandId, type, and title are required" }, { status: 400 });
      }

      // Verify access
      const brand = await prisma.brand.findUnique({
        where: { id: brandId },
        include: { organization: { include: { memberships: true } } },
      });
      if (!brand || !brand.organization.memberships.some((m) => m.userId === user.id)) {
        return NextResponse.json({ error: "Access denied" }, { status: 403 });
      }

      const brief = await createBrief({
        ...body,
        createdById: user.id,
      });

      logMemory({ brandId, userId: user.id, category: "content_brief", action: "created", summary: `Created ${type} content brief: "${title}"`, aiContext: `Created ${type} brief "${title}"` });
      return NextResponse.json(brief, { status: 201 });
    }

    // ── UPDATE ──
    if (body.action === "update") {
      const { briefId } = body;
      if (!briefId) return NextResponse.json({ error: "briefId is required" }, { status: 400 });

      const brief = await updateBrief(briefId, body);
      return NextResponse.json(brief);
    }

    // ── DELETE ──
    if (body.action === "delete") {
      const { briefId } = body;
      if (!briefId) return NextResponse.json({ error: "briefId is required" }, { status: 400 });

      await deleteBrief(briefId);
      return NextResponse.json({ success: true });
    }

    return NextResponse.json({ error: "action must be create, update, or delete" }, { status: 400 });

  } catch (e) {
    console.error("Content brief error:", e);
    return NextResponse.json({ error: "Something went wrong" }, { status: 500 });
  }
}
