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

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

// Unarchive a tour (restore from archive)
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 unarchive 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 unarchive this tour" },
        { status: 403 }
      );
    }

    const tour = await prisma.tour.update({
      where: { id },
      data: {
        archived: false,
        // Note: We don't automatically publish, guide needs to manually publish
      },
    });

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