import { NextRequest, NextResponse } from 'next/server'
import { getDb } from '@/server/db'

export async function GET(
    request: NextRequest,
    { params }: { params: { id: string } }
) {
    try {
        const id = String(params?.id ?? '')
        const db = await getDb()

        const catchVideo = await db.get<{
            id: string
            userId: string
            title: string
            thumb: string | null
            src: string | null
            views: number
            likes: number
            comments: number
            startAt: string | null
            startTs: number | null
            tags: string | null
            status: string | null
            description: string | null
            created_at_sec: number
            updated_at_sec: number
            nickname: string
            verified: number | null
            followers: number
            profile: string | null
        }>(
            `SELECT 
                c.catch_id AS id,
                c.user_id AS userId,
                c.title,
                c.thumbnail_url AS thumb,
                c.video_stream_url AS src,
                0 AS views,
                (SELECT COUNT(1) FROM catch_likes cl WHERE cl.catch_id = c.catch_id) AS likes,
                (SELECT COUNT(1) FROM catch_comments cc WHERE cc.catch_id = c.catch_id) AS comments,
                NULL AS startAt,
                0 AS startTs,
                c.tags,
                NULL AS status,
                c.description,
                c.created_at AS created_at_sec,
                c.updated_at AS updated_at_sec,
                u.display_name as nickname,
                u.is_verified as verified,
                (SELECT COUNT(1) FROM user_actions f WHERE f.target_id = u.user_id AND f.action_type = 'follow') as followers,
                u.avatar_url as profile
            FROM catch c
            JOIN users u ON c.user_id = u.user_id
            WHERE c.catch_id = ?`,
            [id]
        )

        if (!catchVideo) {
            return NextResponse.json(
                { ok: false, error: 'NOT_FOUND' },
                { status: 404 }
            )
        }

        let tags: string[] = []
        if (catchVideo.tags) {
            try {
                tags = JSON.parse(catchVideo.tags)
            } catch {
                tags = catchVideo.tags.split(',').map((t) => t.trim()).filter(Boolean)
            }
        }

        return NextResponse.json({
            ok: true,
            data: {
                id: catchVideo.id,
                userId: catchVideo.userId,
                title: catchVideo.title,
                thumb: catchVideo.thumb || '',
                src: catchVideo.src || '',
                views: catchVideo.views || 0,
                likes: catchVideo.likes || 0,
                comments: catchVideo.comments || 0,
                startAt: catchVideo.startAt || '',
                startTs: catchVideo.startTs || 0,
                tags,
                status: catchVideo.status as 'adult' | undefined,
                description: catchVideo.description || '',
                createdAt: new Date(catchVideo.created_at_sec * 1000).toISOString(),
                updatedAt: new Date(catchVideo.updated_at_sec * 1000).toISOString(),
                nickname: catchVideo.nickname,
                verified: Boolean(catchVideo.verified),
                followers: catchVideo.followers || 0,
                profile: catchVideo.profile || '',
            },
        })
    } catch (error: any) {
        console.error('Failed to fetch catch video:', error)
        return NextResponse.json(
            { ok: false, message: error?.message || 'Failed to fetch catch video' },
            { status: 500 }
        )
    }
}
