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

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

        const { id } = await params;

        const journey = await prisma.journey.findUnique({
            where: { id },
            include: {
                user: { select: { id: true, name: true } },
                blocks: {
                    orderBy: { order: 'asc' },
                },
                photos: {
                    orderBy: { order: 'asc' },
                },
                stops: {
                    orderBy: { order: 'asc' },
                    include: {
                        photos: {
                            orderBy: { order: 'asc' },
                        },
                    },
                },
            },
        });

        if (!journey) {
            return NextResponse.json({ error: 'Journey not found' }, { status: 404 });
        }

        return NextResponse.json(journey);
    } catch (error) {
        console.error('Journey GET 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 } = await params;

        const journey = await prisma.journey.findUnique({ where: { id } });
        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, startDate, endDate, coverPhotoUrl, coverFocalX, coverFocalY } = body;

        if (title !== undefined && (typeof title !== 'string' || title.trim().length === 0)) {
            return NextResponse.json({ error: 'Title cannot be empty' }, { status: 400 });
        }
        if (title && title.length > 200) {
            return NextResponse.json({ error: 'Title must be 200 characters or less' }, { status: 400 });
        }

        const data: Record<string, unknown> = {};
        if (title !== undefined) data.title = title.trim();
        if (description !== undefined) data.description = description || null;
        if (startDate !== undefined) data.startDate = startDate ? new Date(startDate) : null;
        if (endDate !== undefined) data.endDate = endDate ? new Date(endDate) : null;
        if (coverPhotoUrl !== undefined) data.coverPhotoUrl = coverPhotoUrl || null;
        if (coverFocalX !== undefined) data.coverFocalX = coverFocalX ?? null;
        if (coverFocalY !== undefined) data.coverFocalY = coverFocalY ?? null;

        const updated = await prisma.journey.update({
            where: { id },
            data,
            include: {
                user: { select: { id: true, name: true } },
                stops: {
                    orderBy: { order: 'asc' },
                    include: {
                        photos: { orderBy: { order: 'asc' } },
                    },
                },
            },
        });

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

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

        const { id } = await params;

        const journey = await prisma.journey.findUnique({ where: { id } });
        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 });
        }

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

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

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