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

type RouteContext = {
  params: Promise<{ id: string }>;
};

// Archive a tour (soft delete)
export async function POST(req: NextRequest, context: RouteContext) {
  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 archive tours" },
        { status: 403 }
      );
    }

    const { id } = await context.params;

    // Check if tour exists and user owns it
    const existingTour = await prisma.tour.findUnique({
      where: { id },
    });

    if (!existingTour) {
      return NextResponse.json({ error: "Tour not found" }, { status: 404 });
    }

    if (existingTour.createdById !== user.id) {
      return NextResponse.json(
        { error: "You don't have permission to archive this tour" },
        { status: 403 }
      );
    }

    const tour = await prisma.tour.update({
      where: { id },
      data: {
        archived: true,
        published: false, // Unpublish when archiving
      },
    });

    return NextResponse.json({
      message: "Tour archived successfully",
      tour,
    });
  } catch (error) {
    console.error("Error archiving tour:", error);
    return NextResponse.json(
      { error: "Failed to archive tour" },
      { status: 500 }
    );
  }
}
