import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth-utils";
import prisma from "@/lib/db";
import { uploadToS3, deleteFromS3, extractS3Key, validateFile } from "@/lib/s3-upload";

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

const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
const MAX_IMAGES_PER_TOUR = 10;
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/jpg"];

// Upload images for a tour
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 upload tour images" },
        { status: 403 }
      );
    }

    const { id: tourId } = await context.params;

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

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

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

    const formData = await req.formData();
    const files = formData.getAll("images") as File[];

    if (!files || files.length === 0) {
      return NextResponse.json(
        { error: "No images provided" },
        { status: 400 }
      );
    }

    // Maximum 10 images per tour
    if (tour.images.length + files.length > MAX_IMAGES_PER_TOUR) {
      return NextResponse.json(
        { error: `Maximum ${MAX_IMAGES_PER_TOUR} images allowed per tour` },
        { status: 400 }
      );
    }

    const uploadedImages = [];
    let currentMaxOrder = tour.images.length > 0
      ? Math.max(...tour.images.map((img) => img.order))
      : -1;

    for (const file of files) {
      // Validate file
      const validation = validateFile(file, {
        maxSize: MAX_FILE_SIZE,
        allowedTypes: ALLOWED_TYPES,
      });

      if (!validation.valid) {
        console.warn(`Skipping invalid file: ${file.name} - ${validation.error}`);
        continue; // Skip invalid files
      }

      // Convert file to buffer
      const bytes = await file.arrayBuffer();
      const buffer = Buffer.from(bytes);

      // Upload to S3
      const uploadResult = await uploadToS3({
        file: buffer,
        filename: file.name,
        contentType: file.type,
        fileType: "tour-image",
        tourId: tourId,
      });

      console.log(`Uploaded tour image to S3: ${uploadResult.key}`);

      // Create database record with S3 key
      currentMaxOrder++;
      const image = await prisma.tourImage.create({
        data: {
          tourId,
          url: uploadResult.key, // Store S3 key
          altText: file.name.replace(/\.[^/.]+$/, ""),
          order: currentMaxOrder,
        },
      });

      uploadedImages.push({
        ...image,
        signedUrl: uploadResult.url, // Include signed URL for immediate display
      });
    }

    return NextResponse.json({
      message: "Images uploaded successfully",
      images: uploadedImages,
    });
  } catch (error) {
    console.error("Error uploading images:", error);
    return NextResponse.json(
      { error: "Failed to upload images" },
      { status: 500 }
    );
  }
}

// Delete a tour image
export async function DELETE(req: NextRequest, context: RouteContext) {
  try {
    const user = await getCurrentUser();

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

    const { id: tourId } = await context.params;
    const { searchParams } = new URL(req.url);
    const imageId = searchParams.get("imageId");

    if (!imageId) {
      return NextResponse.json(
        { error: "Image ID is required" },
        { status: 400 }
      );
    }

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

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

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

    // Get image to find S3 key
    const image = await prisma.tourImage.findUnique({
      where: { id: imageId, tourId },
    });

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

    // Delete from S3
    const s3Key = extractS3Key(image.url);
    if (s3Key) {
      await deleteFromS3(s3Key);
      console.log(`Deleted tour image from S3: ${s3Key}`);
    }

    // Delete from database
    await prisma.tourImage.delete({
      where: { id: imageId, tourId },
    });

    return NextResponse.json({
      message: "Image deleted successfully",
    });
  } catch (error) {
    console.error("Error deleting image:", error);
    return NextResponse.json(
      { error: "Failed to delete image" },
      { status: 500 }
    );
  }
}
