import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { z } from "zod";

// Validation schema
const createProjectSchema = z.object({
  name: z.string().min(1).max(100),
  description: z.string().max(500).optional(),
  userId: z.string(),
});

// GET /api/projects - List all projects
export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const userId = searchParams.get("userId");

    const projects = await db.project.findMany({
      where: userId ? { userId } : undefined,
      include: {
        sections: true,
        agents: true,
        tasks: true,
        _count: {
          select: {
            tasks: true,
            assets: true,
          },
        },
      },
      orderBy: {
        updatedAt: "desc",
      },
    });

    return NextResponse.json({ projects });
  } catch (error) {
    console.error("Error fetching projects:", error);
    return NextResponse.json(
      { error: "Failed to fetch projects" },
      { status: 500 }
    );
  }
}

// POST /api/projects - Create new project
export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const validated = createProjectSchema.parse(body);

    // Create project with default sections
    const project = await db.project.create({
      data: {
        name: validated.name,
        description: validated.description,
        userId: validated.userId,
        sections: {
          create: [
            { type: "LOGO", status: "PENDING" },
            { type: "ICONS", status: "PENDING" },
            { type: "GRAPHICS", status: "PENDING" },
            { type: "MARKETING", status: "PENDING" },
            { type: "WIREFRAME", status: "PENDING" },
            { type: "CODE", status: "PENDING" },
            { type: "TESTING", status: "PENDING" },
            { type: "DEPLOYMENT", status: "PENDING" },
          ],
        },
        agents: {
          create: [
            {
              name: "Claude Code Master",
              type: "CODE",
              provider: "CLAUDE",
              status: "IDLE",
            },
            {
              name: "GPT-4 Content Writer",
              type: "MARKETING",
              provider: "GPT4",
              status: "IDLE",
            },
            {
              name: "DALL-E Designer",
              type: "DESIGN",
              provider: "DALLE",
              status: "IDLE",
            },
          ],
        },
      },
      include: {
        sections: true,
        agents: true,
      },
    });

    return NextResponse.json({ project }, { status: 201 });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { error: "Invalid input", details: error.errors },
        { status: 400 }
      );
    }

    console.error("Error creating project:", error);
    return NextResponse.json(
      { error: "Failed to create project" },
      { status: 500 }
    );
  }
}
