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

const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp"];

// POST /api/users/me/avatar - Upload user avatar
export async function POST(request: NextRequest) {
  try {
    const user = await getCurrentUser();

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

    const formData = await request.formData();
    const file = formData.get("avatar") as File;

    if (!file) {
      return NextResponse.json(
        { error: "No file provided" },
        { status: 400 }
      );
    }

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

    if (!validation.valid) {
      return NextResponse.json(
        { error: validation.error },
        { status: 400 }
      );
    }

    // Get current user to delete old avatar
    const currentUser = await db.user.findUnique({
      where: { id: user.id },
      select: { image: true },
    });

    // Delete old avatar from S3 if exists
    if (currentUser?.image) {
      const oldKey = extractS3Key(currentUser.image);
      if (oldKey) {
        await deleteFromS3(oldKey);
        console.log(`Deleted old avatar: ${oldKey}`);
      }
    }

    // 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: "avatar",
      userId: user.id,
    });

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

    // Update user's image path in database (store S3 key)
    const updatedUser = await db.user.update({
      where: { id: user.id },
      data: { 
        image: uploadResult.key,
        updatedAt: new Date(),
      },
      select: {
        id: true,
        name: true,
        image: true,
      },
    });

    return NextResponse.json({
      message: "Avatar uploaded successfully",
      user: {
        ...updatedUser,
        imageUrl: uploadResult.url, // Return signed URL for immediate use
      },
    });
  } catch (error) {
    console.error("Error uploading avatar:", error);
    return NextResponse.json(
      { error: "Failed to upload avatar" },
      { status: 500 }
    );
  }
}
