import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import {
  getTasks,
  getTaskCounts,
  createTask,
  updateTask,
  completeTaskAndLaunch,
  TaskStatus,
  TaskCategory,
  TaskPriority,
  TaskEffort,
} from "@/lib/services/tasks";

/**
 * GET /api/tasks?brandId=xxx&status=todo&category=seo
 * Returns tasks for a brand with optional filters.
 * Add ?counts=true to get status counts instead.
 */
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);
  const brandId = searchParams.get("brandId");

  // Empty brandId can happen during brand-context hydration on pages
  // that fire the fetch before brand resolves. Return 200 with an
  // empty list so the client just renders nothing instead of showing
  // a misleading 400 error in the console.
  if (!brandId) return NextResponse.json([], { status: 200 });

  // 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 });
  }

  // Return counts if requested
  if (searchParams.get("counts") === "true") {
    const counts = await getTaskCounts(brandId);
    return NextResponse.json(counts);
  }

  const tasks = await getTasks(brandId, {
    status: searchParams.get("status") as TaskStatus | undefined,
    category: searchParams.get("category") as TaskCategory | undefined,
    priority: searchParams.get("priority") as TaskPriority | undefined,
    assignedTo: searchParams.get("assignedTo") ?? undefined,
  });

  return NextResponse.json(tasks);
}

/**
 * POST /api/tasks
 * Create a task, update a task, or complete+launch.
 * Body: { action: "create" | "update" | "complete_and_launch", ... }
 */
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();
    const { action } = body;

    // ── CREATE ──
    if (action === "create") {
      const { brandId, title, category } = body;
      if (!brandId || !title || !category) {
        return NextResponse.json({ error: "brandId, title, and category 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 task = await createTask({
        brandId,
        title,
        description: body.description,
        category: category as TaskCategory,
        priority: body.priority as TaskPriority,
        effort: body.effort as TaskEffort,
        pageUrl: body.pageUrl,
        recommendation: body.recommendation,
        source: body.source,
        sourceId: body.sourceId,
        sourceRunAt: body.sourceRunAt ? new Date(body.sourceRunAt) : undefined,
        dueDate: body.dueDate ? new Date(body.dueDate) : undefined,
        assignedTo: body.assignedTo,
        preventDuplicate: body.preventDuplicate,
      });

      // Check if it was a duplicate
      if ("_duplicate" in task && task._duplicate) {
        return NextResponse.json({ ...task, _duplicate: true, message: "Task already exists" }, { status: 200 });
      }

      return NextResponse.json(task, { status: 201 });
    }

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

      const task = await updateTask(taskId, {
        title: body.title,
        description: body.description,
        category: body.category,
        priority: body.priority,
        effort: body.effort,
        status: body.status,
        pageUrl: body.pageUrl,
        dueDate: body.dueDate ? new Date(body.dueDate) : body.dueDate,
        assignedTo: body.assignedTo,
      });

      return NextResponse.json(task);
    }

    // ── COMPLETE AND LAUNCH ──
    if (action === "complete_and_launch") {
      const { taskId } = body;
      if (!taskId) return NextResponse.json({ error: "taskId is required" }, { status: 400 });

      const result = await completeTaskAndLaunch(taskId, body.launch);
      return NextResponse.json(result);
    }

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

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