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

export async function POST(request: NextRequest) {
    try {
        const body = await request.json()
        const { email } = body

        if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(email).trim())) {
            return NextResponse.json(
                { ok: false, message: 'Invalid email format' },
                { status: 400 }
            )
        }
        const userId = await validateSession(request)
        if (!userId) {
            return NextResponse.json({ ok: false, message: 'Unauthorized' }, { status: 401 })
        }
        const db = await getDb()
        await db.run(
            `UPDATE users SET email = ?, updated_at = CAST(strftime('%s','now') AS INTEGER) WHERE user_id = ?`,
            [String(email).trim(), userId]
        )

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

