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 }> }) {
    try {
        const session = await requireAuthenticatedUser();
        if (!session) return unauthorizedResponse();

        const { id: journeyId, stopId } = 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 stop = await prisma.journeyStop.findUnique({ where: { id: stopId } });
        if (!stop || stop.journeyId !== journeyId) {
            return NextResponse.json({ error: 'Stop not found' }, { status: 404 });
        }

        const body = await req.json();
        const { title, description, latitude, longitude, locationName, arrivalDate } = body;

        const data: Record<string, unknown> = {};
        if (title !== undefined) data.title = title?.trim() || stop.title;
        if (description !== undefined) data.description = description || null;
        if (latitude !== undefined) data.latitude = latitude ?? null;
        if (longitude !== undefined) data.longitude = longitude ?? null;
        if (locationName !== undefined) data.locationName = locationName || null;
        if (arrivalDate !== undefined) data.arrivalDate = arrivalDate ? new Date(arrivalDate) : null;

        const updated = await prisma.journeyStop.update({
            where: { id: stopId },
            data,
            include: { photos: { orderBy: { order: 'asc' } } },
        });

        return NextResponse.json(updated);
    } catch (error) {
        console.error('Stop 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 }> }) {
    try {
        const session = await requireAuthenticatedUser();
        if (!session) return unauthorizedResponse();

        const { id: journeyId, stopId } = 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 stop = await prisma.journeyStop.findUnique({ where: { id: stopId } });
        if (!stop || stop.journeyId !== journeyId) {
            return NextResponse.json({ error: 'Stop not found' }, { status: 404 });
        }

        // Delete uploaded photos from disk
        const { rm } = await import('fs/promises');
        const path = await import('path');
        try {
            const stopDir = path.join(process.cwd(), 'public', 'uploads', 'journeys', journeyId, stopId);
            await rm(stopDir, { recursive: true, force: true });
        } catch {
            // Directory may not exist
        }

        await prisma.journeyStop.delete({ where: { id: stopId } });

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