import { NextRequest, NextResponse } from 'next/server'
import { getDb } from '@/server/db'
import { validateSession } from '@/app/api/_helpers/session'

export async function PATCH(
    request: NextRequest,
    { params }: { params: { id: string; commentId: string } }
) {
    try {
        const catchId = String(params?.id ?? '')
        const commentId = String(params?.commentId ?? '')
        const userId = await validateSession(request)

        if (!userId) {
            return NextResponse.json(
                { ok: false, error: 'UNAUTHORIZED' },
                { status: 401 }
            )
        }

        const body = await request.json()
        const { content } = body

        if (!content || !content.trim()) {
            return NextResponse.json(
                { ok: false, error: 'MISSING_FIELDS' },
                { status: 400 }
            )
        }

        const db = await getDb()

        const comment = await db.get<{ userId: string; catchId: string }>(
            `SELECT user_id AS userId, catch_id AS catchId FROM catch_comments WHERE comment_id = ?`,
            [commentId]
        )

        if (!comment) {
            return NextResponse.json(
                { ok: false, error: 'COMMENT_NOT_FOUND' },
                { status: 404 }
            )
        }

        if (comment.catchId !== catchId) {
            return NextResponse.json(
                { ok: false, error: 'FORBIDDEN' },
                { status: 403 }
            )
        }

        // 驗證留言是否屬於當前用戶
        if (comment.userId !== userId) {
            return NextResponse.json(
                { ok: false, error: 'FORBIDDEN' },
                { status: 403 }
            )
        }

        const editedAtSec = Math.floor(Date.now() / 1000)
        const editedAtIso = new Date(editedAtSec * 1000).toISOString()

        await db.run(
            `UPDATE catch_comments SET contents = ?, edited_at = ? WHERE comment_id = ?`,
            [content.trim(), editedAtSec, commentId]
        )

        return NextResponse.json({
            ok: true,
            data: {
                id: commentId,
                content: content.trim(),
                editedAt: editedAtIso,
            },
        })
    } catch (error: any) {
        console.error('Failed to edit comment:', error)
        return NextResponse.json(
            { ok: false, message: error?.message || 'Failed to edit comment' },
            { status: 500 }
        )
    }
}

