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

export async function GET(request: NextRequest) {
    try {
        const { searchParams } = new URL(request.url)
        const limit = parseInt(searchParams.get('limit') || '20', 10)
        const offset = parseInt(searchParams.get('offset') || '0', 10)
        const sort = searchParams.get('sort') || 'recent' // 'recent' 或 'popular'

        const db = await getDb()

        type CatchVideoRow = {
            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
        }

        let orderByClause = 'ORDER BY c.created_at DESC'
        if (sort === 'popular') {
            orderByClause = `ORDER BY (
                (SELECT COUNT(1) FROM catch_likes cl WHERE cl.catch_id = c.catch_id) * 0.7 +
                (SELECT COUNT(1) FROM catch_comments cc WHERE cc.catch_id = c.catch_id) * 0.3
            ) DESC, c.created_at DESC`
        }

        const catchVideosResult = await db.all<CatchVideoRow>(
            `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.is_show = 1
            ${orderByClause}
            LIMIT ? OFFSET ?`,
            [limit, offset]
        )

        const catchVideos: CatchVideoRow[] = Array.isArray(catchVideosResult) ? catchVideosResult : []

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

            return {
                id: video.id,
                userId: video.userId,
                title: video.title,
                thumb: video.thumb || '',
                src: video.src || '',
                views: video.views || 0,
                likes: video.likes || 0,
                comments: video.comments || 0,
                startAt: video.startAt || '',
                startTs: video.startTs || 0,
                tags,
                status: video.status as 'adult' | undefined,
                description: video.description || '',
                createdAt: new Date(video.created_at_sec * 1000).toISOString(),
                updatedAt: new Date(video.updated_at_sec * 1000).toISOString(),
                nickname: video.nickname,
                verified: Boolean(video.verified),
                followers: video.followers || 0,
                profile: video.profile || '',
            }
        })

        return NextResponse.json({
            ok: true,
            data: videos,
        })
    } catch (error: any) {
        console.error('Failed to fetch catch videos:', error)
        return NextResponse.json(
            { ok: false, message: error?.message || 'Failed to fetch catch videos' },
            { status: 500 }
        )
    }
}
