import { NextResponse } from 'next/server'
import bcrypt from 'bcryptjs'
import { getDb } from '@/server/db'
import { newUserId } from '@/server/userIdUtils'

export const runtime = 'nodejs'

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

export async function POST(req: Request) {
    try {
        const body = await req.json().catch(() => ({}))
        const account = String(body?.account ?? '').trim()
        const password = String(body?.password ?? '').trim()
        const email = String(body?.email ?? '').trim()
        if (!account || account.length < 6 || account.length > 12 || !/^[A-Za-z0-9]+$/.test(account)) {
            return json({ ok: false, error: 'INVALID_ACCOUNT' }, { status: 400 })
        }
        if (!password || password.length < 10 || password.length > 15) {
            return json({ ok: false, error: 'INVALID_PASSWORD' }, { status: 400 })
        }
        if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            return json({ ok: false, error: 'INVALID_EMAIL' }, { status: 400 })
        }
        const db = await getDb()
        const existingUser = await db.get<{ id: string }>(
            `SELECT user_id AS id FROM users WHERE account = ?`,
            [account]
        )
        if (existingUser) {
            return json({ ok: false, error: 'ACCOUNT_EXISTS' }, { status: 409 })
        }
        const existingEmail = await db.get<{ id: string }>(
            `SELECT user_id AS id FROM users WHERE email = ?`,
            [email]
        )
        if (existingEmail) {
            return json({ ok: false, error: 'EMAIL_EXISTS' }, { status: 409 })
        }
        const passwordHash = await bcrypt.hash(password, 10)
        const nowSec = Math.floor(Date.now() / 1000)
        const userId = newUserId()
        await db.run(
            `INSERT INTO users (user_id, display_id, display_name, account, password_hash, email, created_at, updated_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
            [userId, account, account, account, passwordHash, email, nowSec, nowSec]
        )
        const user = await db.get<{
            id: string
            displayName: string
            email: string
            avatar: string | null
            banner: string | null
            description: string | null
            followersCount: number
            totalViewsCount: number
            createdAt: string
        }>(
            `SELECT u.user_id AS id, u.display_name AS displayName, COALESCE(u.email, '') AS email, u.avatar_url AS avatar, u.banner_url AS banner,
                    '' AS description,
                    (SELECT COUNT(1) FROM user_actions f WHERE f.target_id = u.user_id AND f.action_type = 'follow') AS followersCount,
                    0 AS totalViewsCount,
                    (u.created_at * 1000) AS createdAt
             FROM users u WHERE u.user_id = ?`,
            [userId]
        )
        return json({ ok: true, data: user }, { status: 201 })
    } catch (error) {
        console.error('Register error:', error)
        return json({ ok: false, error: 'INTERNAL_ERROR' }, { status: 500 })
    }
}

