import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { requireAuthenticatedUser, canModifyJourney, unauthorizedResponse } from '@/lib/api-auth';

export async function PUT(
    req: NextRequest,
    { params }: { params: Promise<{ id: string; stopId: string; photoId: string }> }
) {
    try {
        const session = await requireAuthenticatedUser();
        if (!session) return unauthorizedResponse();

        const { id: journeyId, stopId, photoId } = await params;

        const journey = await prisma.journey.findUnique({ where: { id: journeyId } });
        if (!journey) {
            return NextResponse.json({ error: 'Journey not found' }, { status: 404 });
        }
        if (!canModifyJourney(session as { user: { id: string; role?: string } }, journey.userId)) {
            return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
        }

        const photo = await prisma.journeyPhoto.findUnique({ where: { id: photoId } });
        if (!photo || photo.stopId !== stopId) {
            return NextResponse.json({ error: 'Photo not found' }, { status: 404 });
        }

        const body = await req.json();
        const { caption } = body;

        const data: Record<string, unknown> = {};
        if (caption !== undefined) data.caption = caption || null;

        const updated = await prisma.journeyPhoto.update({
            where: { id: photoId },
            data,
        });

        return NextResponse.json(updated);
    } catch (error) {
        console.error('Journey photo PUT error:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}

export async function DELETE(
    req: NextRequest,
    { params }: { params: Promise<{ id: string; stopId: string; photoId: string }> }
) {
    try {
        const session = await requireAuthenticatedUser();
        if (!session) return unauthorizedResponse();

        const { id: journeyId, stopId, photoId } = await params;

        const journey = await prisma.journey.findUnique({ where: { id: journeyId } });
        if (!journey) {
            return NextResponse.json({ error: 'Journey not found' }, { status: 404 });
        }
        if (!canModifyJourney(session as { user: { id: string; role?: string } }, journey.userId)) {
            return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
        }

        const photo = await prisma.journeyPhoto.findUnique({ where: { id: photoId } });
        if (!photo || photo.stopId !== stopId) {
            return NextResponse.json({ error: 'Photo not found' }, { status: 404 });
        }

        // Delete file from disk if it's an uploaded file (not an archive reference)
        if (!photo.photoId && photo.url.startsWith('/uploads/journeys/')) {
            const { unlink } = await import('fs/promises');
            const path = await import('path');
            try {
                await unlink(path.join(process.cwd(), 'public', photo.url));
            } catch {
                // File may not exist
            }
        }

        await prisma.journeyPhoto.delete({ where: { id: photoId } });

        return NextResponse.json({ success: true });
    } catch (error) {
        console.error('Journey photo DELETE error:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}
