import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { writeFile, mkdir } from "fs/promises";
import { join } from "path";
import { randomUUID } from "crypto";

// Max file size: 10MB
const MAX_FILE_SIZE = 10 * 1024 * 1024;

const ALLOWED_MIME_TYPES = [
    "image/jpeg",
    "image/png",
    "image/gif",
    "image/webp",
    "application/pdf",
    "application/msword",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "text/plain",
    "text/csv",
];

export async function POST(req: NextRequest) {
    const user = await getCurrentUser();
    if (!user) {
        return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    try {
        const formData = await req.formData();
        const file = formData.get("file") as File | null;
        const messageId = formData.get("messageId") as string | null;
        const conversationId = formData.get("conversationId") as string | null;

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

        if (!messageId || !conversationId) {
            return NextResponse.json({ error: "Missing messageId or conversationId" }, { status: 400 });
        }

        // Validate file size
        if (file.size > MAX_FILE_SIZE) {
            return NextResponse.json(
                { error: `File too large. Maximum size is ${MAX_FILE_SIZE / (1024 * 1024)}MB` },
                { status: 400 }
            );
        }

        // Validate MIME type
        if (!ALLOWED_MIME_TYPES.includes(file.type)) {
            return NextResponse.json(
                { error: "File type not allowed. Supported: images, PDF, Word, Excel, CSV, TXT" },
                { status: 400 }
            );
        }

        // Verify user is a conversation participant
        const membership = await prisma.conversationParticipant.findUnique({
            where: {
                conversation_id_user_id: {
                    conversation_id: conversationId,
                    user_id: user.id,
                },
            },
        });

        if (!membership || membership.left_at) {
            return NextResponse.json({ error: "Not a member of this conversation" }, { status: 403 });
        }

        // Create upload directory
        const uploadsDir = join(process.cwd(), "public", "uploads", "messages");
        await mkdir(uploadsDir, { recursive: true });

        // Generate unique filename
        const ext = file.name.split(".").pop() || "bin";
        const uniqueName = `${randomUUID()}.${ext}`;
        const filePath = join(uploadsDir, uniqueName);

        // Write file to disk
        const bytes = await file.arrayBuffer();
        const buffer = Buffer.from(bytes);
        await writeFile(filePath, buffer);

        const fileUrl = `/uploads/messages/${uniqueName}`;

        // Create attachment record
        const attachment = await prisma.messageAttachment.create({
            data: {
                message_id: messageId,
                filename: file.name,
                file_url: fileUrl,
                file_size: file.size,
                mime_type: file.type,
                uploaded_by: user.id,
                thumbnail_url: file.type.startsWith("image/") ? fileUrl : null,
            },
        });

        // Push real-time event via internal API route
        const baseUrl = process.env.NEXTAUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";
        fetch(`${baseUrl}/api/messages/push`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "x-internal-secret": process.env.INTERNAL_API_SECRET || "internal-push-secret-key",
            },
            body: JSON.stringify({
                conversationId,
                event: {
                    type: "new_attachment",
                    messageId: messageId,
                    attachment: {
                        id: attachment.id,
                        filename: attachment.filename,
                        fileUrl: attachment.file_url,
                        fileSize: attachment.file_size,
                        mimeType: attachment.mime_type,
                        thumbnailUrl: attachment.thumbnail_url,
                    },
                    timestamp: new Date().toISOString(),
                },
                excludeUserId: user.id,
            }),
        }).catch((err) => console.error("[Realtime] Push attachment failed:", err));

        return NextResponse.json({
            success: true,
            attachment: {
                id: attachment.id,
                filename: attachment.filename,
                file_url: attachment.file_url,
                file_size: attachment.file_size,
                mime_type: attachment.mime_type,
                thumbnail_url: attachment.thumbnail_url,
            },
        });
    } catch (error) {
        console.error("File upload failed:", error);
        return NextResponse.json(
            { error: "Failed to upload file" },
            { status: 500 }
        );
    }
}
