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

export async function GET(request: NextRequest) {
    try {
        const userId = await getUserIdFromRequest(request)

        if (!userId) {
            return NextResponse.json(
                { ok: false, message: 'Unauthorized' },
                { status: 401 }
            )
        }

        const searchParams = request.nextUrl.searchParams
        const period = Number(searchParams.get('period') || '7')
        const page = Number(searchParams.get('page') || '1')
        const pageSize = Number(searchParams.get('pageSize') || '15')

        const db = await getDb()

        const nowSec = Math.floor(Date.now() / 1000)
        const periodSec = period * 24 * 60 * 60
        const startTimeSec = nowSec - periodSec

        const totalResult = await db.get<{ count: number }>(USER_LOGIN_HISTORY_SQL.countInPeriod, [
            userId,
            startTimeSec,
        ])
        const total = totalResult?.count || 0

        const maxIpResult = await db.get<{ ip_address: string; count: number }>(
            USER_LOGIN_HISTORY_SQL.maxIpInPeriod,
            [userId, startTimeSec]
        )
        const maxIp = maxIpResult?.ip_address || ''

        const offset = (page - 1) * pageSize
        const records = await db.all<{
            history_id: string
            connect_at: number
            ip_address: string
            country_code: string | null
        }>(USER_LOGIN_HISTORY_SQL.pageInPeriod, [userId, startTimeSec, pageSize, offset])

        return NextResponse.json({
            ok: true,
            records: records.map((r) => ({
                id: r.history_id,
                connDate: new Date(r.connect_at * 1000).toISOString(),
                ipInfo: r.ip_address,
                country: r.country_code || '-',
                countryEng: '',
            })),
            total,
            maxIp,
        })
    } catch (error: any) {
        console.error('Failed to fetch login history:', error)
        return NextResponse.json(
            { ok: false, message: error?.message || 'Failed to fetch login history' },
            { status: 500 }
        )
    }
}

