import { NextRequest, NextResponse } from 'next/server'
import { getDb } from '@/server/db'
import { resolveUserKeyToUserId } from '@/server/userIdUtils'
import { getUserIdFromRequest } from '../../../_helpers/session'

export const runtime = 'nodejs'

function json(data: unknown, init?: ResponseInit) {
    return NextResponse.json(data, init)
}

export async function POST(req: NextRequest, ctx: { params: { id: string } }) {
    try {
        const targetKey = String(ctx?.params?.id ?? '').trim()
        if (!targetKey) return json({ ok: false, error: 'BAD_REQUEST' }, { status: 400 })
        const followerKey = await getUserIdFromRequest(req)
        if (!followerKey) {
            return json({ ok: false, error: 'UNAUTHORIZED', message: '請先登入' }, { status: 401 })
        }
        const db = await getDb()
        const targetUserId = await resolveUserKeyToUserId(db, targetKey)
        const followerId = (await resolveUserKeyToUserId(db, followerKey)) ?? followerKey
        if (!targetUserId) return json({ ok: false, error: 'NOT_FOUND', message: '使用者不存在' }, { status: 404 })
        if (targetUserId === followerId) {
            return json({ ok: false, error: 'BAD_REQUEST', message: '不能關注自己' }, { status: 400 })
        }
        const nowSec = Math.floor(Date.now() / 1000)
        const exists = await db.get<{ c: number }>(
            `SELECT 1 AS c FROM user_actions WHERE user_id = ? AND target_id = ? AND action_type = 'follow' LIMIT 1`,
            [followerId, targetUserId]
        )
        let isFollowing = false
        if (exists?.c) {
            const deleteResult = await db.run(
                `DELETE FROM user_actions WHERE user_id = ? AND target_id = ? AND action_type = 'follow'`,
                [followerId, targetUserId]
            )
            console.log('Delete follow result:', deleteResult)
            isFollowing = false
        } else {
            const insertResult = await db.run(
                `INSERT OR IGNORE INTO user_actions (user_id, target_id, action_type, created_at) VALUES (?, ?, 'follow', ?)`,
                [followerId, targetUserId, nowSec]
            )
            console.log('Insert follow result:', insertResult)
            isFollowing = true
        }
        const user = await db.get<{ followersCount: number }>(
            `SELECT COUNT(1) AS followersCount FROM user_actions WHERE target_id = ? AND action_type = 'follow'`,
            [targetUserId]
        )
        return json({ ok: true, data: { userId: targetUserId, isFollowing, followersCount: Number(user?.followersCount ?? 0) } })
    } catch (error: any) {
        console.error('Failed to toggle follow:', error)
        return json({ ok: false, error: 'INTERNAL_ERROR', message: error?.message || '操作失敗' }, { status: 500 })
    }
}

export async function GET(req: NextRequest, ctx: { params: { id: string } }) {
    const targetKey = String(ctx?.params?.id ?? '').trim()
    if (!targetKey) return json({ ok: false, error: 'BAD_REQUEST' }, { status: 400 })
    const followerKey = await getUserIdFromRequest(req)
    if (!followerKey) {
        return json({ ok: true, data: { isFollowing: false } })
    }
    const db = await getDb()
    const targetUserId = await resolveUserKeyToUserId(db, targetKey)
    if (!targetUserId) {
        return json({ ok: true, data: { isFollowing: false } })
    }
    const followerId = (await resolveUserKeyToUserId(db, followerKey)) ?? followerKey
    const exists = await db.get<{ c: number }>(
        `SELECT 1 AS c FROM user_actions WHERE user_id = ? AND target_id = ? AND action_type = 'follow' LIMIT 1`,
        [followerId, targetUserId]
    )
    return json({ ok: true, data: { isFollowing: Boolean(exists?.c) } })
}


