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 blockerKey = await getUserIdFromRequest(req)
        if (!blockerKey) {
            return json({ ok: false, error: 'UNAUTHORIZED', message: '請先登入' }, { status: 401 })
        }
        const db = await getDb()
        const targetUserId = await resolveUserKeyToUserId(db, targetKey)
        const blockerId = (await resolveUserKeyToUserId(db, blockerKey)) ?? blockerKey
        if (!targetUserId) return json({ ok: false, error: 'NOT_FOUND', message: '使用者不存在' }, { status: 404 })
        if (targetUserId === blockerId) {
            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 = 'block' LIMIT 1`,
            [blockerId, targetUserId]
        )
        let isBlocked = false
        if (exists?.c) {
            await db.run(
                `DELETE FROM user_actions WHERE user_id = ? AND target_id = ? AND action_type = 'block'`,
                [blockerId, targetUserId]
            )
            isBlocked = false
        } else {
            await db.run(
                `INSERT OR IGNORE INTO user_actions (user_id, target_id, action_type, created_at) VALUES (?, ?, 'block', ?)`,
                [blockerId, targetUserId, nowSec]
            )
            const followExists = await db.get<{ c: number }>(
                `SELECT 1 AS c FROM user_actions WHERE user_id = ? AND target_id = ? AND action_type = 'follow' LIMIT 1`,
                [blockerId, targetUserId]
            )
            if (followExists?.c) {
                await db.run(
                    `DELETE FROM user_actions WHERE user_id = ? AND target_id = ? AND action_type = 'follow'`,
                    [blockerId, targetUserId]
                )
            }
            isBlocked = 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, isBlocked, followersCount: Number(user?.followersCount ?? 0) } })
    } catch (error: any) {
        console.error('Failed to toggle block:', 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 blockerKey = await getUserIdFromRequest(req)
    if (!blockerKey) {
        return json({ ok: true, data: { isBlocked: false } })
    }
    const db = await getDb()
    const targetUserId = await resolveUserKeyToUserId(db, targetKey)
    if (!targetUserId) {
        return json({ ok: true, data: { isBlocked: false } })
    }
    const blockerId = (await resolveUserKeyToUserId(db, blockerKey)) ?? blockerKey
    const exists = await db.get<{ c: number }>(
        `SELECT 1 AS c FROM user_actions WHERE user_id = ? AND target_id = ? AND action_type = 'block' LIMIT 1`,
        [blockerId, targetUserId]
    )
    return json({ ok: true, data: { isBlocked: Boolean(exists?.c) } })
}

