import { prisma } from "@/lib/prisma";
import { requireUser, requirePermission, withGuard } from "@/lib/guard";
import { parseBody, ok } from "@/lib/http";
import { createPostSchema } from "@/lib/validators";
import { isManagerTier } from "@/lib/rbac";
import type { Prisma } from "@prisma/client";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

const INCLUDE = {
  author: { select: { id: true, name: true, position: true } },
  reviewer: { select: { id: true, name: true } },
  platforms: { select: { id: true, name: true } },
} satisfies Prisma.PostInclude;

// GET /api/posts — list posts. Manager-tier sees everyone's; staff see only
// the posts they authored. Optional ?status= filter.
export const GET = withGuard(async (req: Request) => {
  const me = await requireUser();
  const url = new URL(req.url);
  const status = url.searchParams.get("status");

  const where: Prisma.PostWhereInput = {};
  if (!isManagerTier(me.role)) where.authorId = me.id;
  if (status) where.status = status as Prisma.PostWhereInput["status"];

  const posts = await prisma.post.findMany({
    where,
    include: INCLUDE,
    orderBy: [{ updatedAt: "desc" }],
  });
  return ok(posts);
});

// POST /api/posts — a marketing staff member drafts a new post (FR-3).
export const POST = withGuard(async (req: Request) => {
  const me = await requirePermission("posts:author");
  const data = await parseBody(req, createPostSchema);

  // Only attach platforms that exist and are active.
  const platforms = await prisma.platform.findMany({
    where: { id: { in: data.platformIds }, active: true },
    select: { id: true },
  });
  if (platforms.length === 0)
    return ok({ error: "Select at least one active platform" }, 400);

  const post = await prisma.post.create({
    data: {
      title: data.title,
      content: data.content,
      mediaUrl: data.mediaUrl || null,
      mediaNotes: data.mediaNotes || null,
      scheduledDate: data.scheduledDate ? new Date(data.scheduledDate) : null,
      status: data.submit ? "PENDING_APPROVAL" : "DRAFT",
      authorId: me.id,
      platforms: { connect: platforms.map((p) => ({ id: p.id })) },
    },
    include: INCLUDE,
  });
  return ok(post, 201);
});
