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(email)) {
            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()
        const existing = await db.get<{ user_id: string }>(
            `SELECT user_id FROM users WHERE email = ? AND user_id != ? LIMIT 1`,
            [email.trim(), userId]
        )
        if (existing) {
            return NextResponse.json(
                { ok: false, message: 'Email already in use' },
                { status: 409 }
            )
        }

        // TODO: 發送驗證郵件
        // 這裡應該發送驗證碼到郵箱，並將驗證碼儲存在 session 或臨時表中

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

