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

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

        const { id: journeyId } = 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 body = await req.json();
        const { title, description, latitude, longitude, locationName, arrivalDate } = body;

        if (!title || typeof title !== 'string' || title.trim().length === 0) {
            return NextResponse.json({ error: 'Title is required' }, { status: 400 });
        }

        const maxOrder = await prisma.journeyStop.aggregate({
            where: { journeyId },
            _max: { order: true },
        });
        const newOrder = (maxOrder._max.order ?? -1) + 1;

        const stop = await prisma.journeyStop.create({
            data: {
                journeyId,
                title: title.trim(),
                description: description || null,
                latitude: latitude ?? null,
                longitude: longitude ?? null,
                locationName: locationName || null,
                arrivalDate: arrivalDate ? new Date(arrivalDate) : null,
                order: newOrder,
            },
            include: { photos: true },
        });

        return NextResponse.json(stop, { status: 201 });
    } catch (error) {
        console.error('Stop POST error:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}

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

        const { id: journeyId } = 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 body = await req.json();
        const { orderedIds } = body;

        if (!Array.isArray(orderedIds)) {
            return NextResponse.json({ error: 'orderedIds array is required' }, { status: 400 });
        }

        // Update order for each stop
        await Promise.all(
            orderedIds.map((id: string, index: number) =>
                prisma.journeyStop.update({
                    where: { id },
                    data: { order: index },
                })
            )
        );

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