import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth-utils";
import prisma from "@/lib/db";
import { z } from "zod";

const createTourSchema = z.object({
  title: z.string().min(5, "Title must be at least 5 characters"),
  description: z.string().min(20, "Description must be at least 20 characters"),
  city: z.string().min(2, "City is required"),
  meetingPoint: z.string().optional(),
  meetingPointLat: z.number().optional(),
  meetingPointLng: z.number().optional(),
  durationMin: z.number().min(30, "Duration must be at least 30 minutes"),
  priceCents: z.number().min(0, "Price must be positive"),
  maxGuests: z.number().min(1, "At least 1 guest required").max(100),
  included: z.array(z.string()).default([]),
  tags: z.array(z.string()).default([]),
  published: z.boolean().default(false),
});

// Create a new tour
export async function POST(req: NextRequest) {
  try {
    const user = await getCurrentUser();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    if (user.role !== "GUIDE") {
      return NextResponse.json(
        { error: "Only guides can create tours" },
        { status: 403 }
      );
    }

    const body = await req.json();
    const validatedData = createTourSchema.parse(body);

    // Generate slug from title
    const slug = validatedData.title
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/(^-|-$)/g, "");

    // Check if slug already exists
    const existingTour = await prisma.tour.findUnique({
      where: { slug },
    });

    let finalSlug = slug;
    if (existingTour) {
      // Append random string to make slug unique
      finalSlug = `${slug}-${Math.random().toString(36).substring(2, 8)}`;
    }

    const tour = await prisma.tour.create({
      data: {
        ...validatedData,
        slug: finalSlug,
        createdById: user.id,
      },
      include: {
        images: true,
        createdBy: {
          select: {
            id: true,
            name: true,
            email: true,
            image: true,
          },
        },
      },
    });

    return NextResponse.json({ tour }, { status: 201 });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { error: "Validation error", details: error.issues },
        { status: 400 }
      );
    }

    console.error("Error creating tour:", error);
    return NextResponse.json(
      { error: "Failed to create tour" },
      { status: 500 }
    );
  }
}

// Get all tours for the current user (guide's dashboard)
export async function GET(req: NextRequest) {
  try {
    const user = await getCurrentUser();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    if (user.role !== "GUIDE") {
      return NextResponse.json(
        { error: "Only guides can access this endpoint" },
        { status: 403 }
      );
    }

    const { searchParams } = new URL(req.url);
    const includeArchived = searchParams.get("includeArchived") === "true";

    const tours = await prisma.tour.findMany({
      where: {
        createdById: user.id,
        ...(includeArchived ? {} : { archived: false }),
      },
      include: {
        images: {
          orderBy: {
            order: "asc",
          },
        },
        _count: {
          select: {
            bookings: true,
            reviews: true,
          },
        },
      },
      orderBy: {
        createdAt: "desc",
      },
    });

    return NextResponse.json({ tours });
  } catch (error) {
    console.error("Error fetching tours:", error);
    return NextResponse.json(
      { error: "Failed to fetch tours" },
      { status: 500 }
    );
  }
}
