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

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

        const body = await req.json();
        const data: Record<string, unknown> = {};

        if (body.text !== undefined) data.text = body.text;
        if (body.latitude !== undefined) data.latitude = body.latitude;
        if (body.longitude !== undefined) data.longitude = body.longitude;
        if (body.locationName !== undefined) data.locationName = body.locationName;
        if (body.focalX !== undefined) data.focalX = body.focalX;
        if (body.focalY !== undefined) data.focalY = body.focalY;
        if (body.images !== undefined) data.images = body.images;

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

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

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

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

        // Delete uploaded file
        if (block.type === 'image' && block.imageUrl && !block.photoId && block.imageUrl.startsWith('/uploads/')) {
            const { unlink } = await import('fs/promises');
            const path = await import('path');
            try { await unlink(path.join(process.cwd(), 'public', block.imageUrl)); } catch { /* ok */ }
        }

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

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