import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth-utils";
import db from "@/lib/db";
import { auth } from "@/lib/auth";
import { headers } from "next/headers";
import { sendAccountDeletionEmail } from "@/lib/email";

/**
 * DELETE /api/users/me/delete
 * Permanently deletes the authenticated user's account and all related data
 * 
 * This will delete:
 * - User profile
 * - All tours created by the user (if Guide)
 * - All bookings made by the user
 * - All reviews written by the user
 * - All invitations sent/received
 * - Sessions and accounts
 * 
 * Note: Related data is deleted via Prisma cascade rules
 */
export async function DELETE() {
  try {
    const user = await getCurrentUser();

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

    const userId = user.id;
    const userEmail = user.email;
    const userName = user.name || "User";

    // Start a transaction to ensure all-or-nothing deletion
    await db.$transaction(async (tx) => {
      // 1. Delete all invitations (both sent and received)
      await tx.invitation.deleteMany({
        where: {
          OR: [
            { inviterId: userId },
            { inviteeId: userId }
          ]
        }
      });

      // 2. Delete all reviews written by the user
      await tx.review.deleteMany({
        where: { userId }
      });

      // 3. Delete all bookings made by the user
      await tx.booking.deleteMany({
        where: { userId }
      });

      // 4. If user is a GUIDE, delete all their tours
      // (This will cascade delete: tour images, tour hosts, bookings, reviews, invitations related to those tours)
      if (user.role === "GUIDE") {
        await tx.tour.deleteMany({
          where: { createdById: userId }
        });
      }

      // 5. Delete tour host relationships
      await tx.tourHost.deleteMany({
        where: { userId }
      });

      // 6. Delete sessions and accounts (handled by cascade in schema, but we'll be explicit)
      await tx.session.deleteMany({
        where: { userId }
      });

      await tx.account.deleteMany({
        where: { userId }
      });

      // 7. Finally, delete the user
      await tx.user.delete({
        where: { id: userId }
      });
    });

    // Invalidate the session after successful deletion
    try {
      await auth.api.signOut({
        headers: await headers()
      });
    } catch {
      // Session might already be invalidated, continue
    }

    // Send confirmation email (don't fail if email fails)
    try {
      await sendAccountDeletionEmail({
        userName,
        userEmail,
      });
    } catch (emailError) {
      console.error("Failed to send deletion confirmation email:", emailError);
      // Continue anyway - account is already deleted
    }

    return NextResponse.json(
      { 
        success: true,
        message: "Account successfully deleted" 
      },
      { status: 200 }
    );

  } catch (error) {
    console.error("Error deleting user account:", error);
    return NextResponse.json(
      { 
        error: "Failed to delete account",
        details: error instanceof Error ? error.message : "Unknown error"
      },
      { status: 500 }
    );
  }
}
