import { NextRequest, NextResponse } from 'next/server'
import { getDb } from '@/server/db'
import { validateSession } from '../../_helpers/session'
import {
    DESKTOP_NOTIFICATION_SETTING_ID,
    mergeNotificationSettingsFromDb,
} from '@/lib/notifications/notificationSettingCatalog'
import { assertValidSettingPayload } from '@/server/notifications/getUserNotificationPrefs'
import { pickRowNumber, pickRowString } from '@/server/pgRow'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

export async function GET(request: NextRequest) {
    try {
        const userId = await validateSession(request)
        if (!userId) {
            return NextResponse.json({ ok: false, message: 'Unauthorized' }, { status: 401 })
        }

        const db = await getDb()
        const rows = await db.all<Record<string, unknown>>(
            `SELECT notification_setting_id AS id, push_enabled AS pushEnabled, record_enabled AS recordEnabled
             FROM user_notification_settings
             WHERE user_id = ?`,
            [userId]
        )

        const parsed = rows.map((row) => ({
            id: pickRowString(row, 'id', 'notification_setting_id'),
            pushEnabled: pickRowNumber(row, 'pushEnabled', 'push_enabled') === 1,
            recordEnabled: pickRowNumber(row, 'recordEnabled', 'record_enabled') === 1,
        }))

        const merged = mergeNotificationSettingsFromDb(parsed)

        return NextResponse.json({
            ok: true,
            desktopNotificationEnabled: merged.desktopNotificationEnabled,
            settings: [
                ...merged.settings,
                {
                    id: DESKTOP_NOTIFICATION_SETTING_ID,
                    pushEnabled: merged.desktopNotificationEnabled,
                    recordEnabled: false,
                },
            ],
        })
    } catch (error: unknown) {
        console.error('Failed to fetch notification settings:', error)
        return NextResponse.json(
            {
                ok: false,
                message: error instanceof Error ? error.message : 'Failed to fetch notification settings',
            },
            { status: 500 }
        )
    }
}

export async function POST(request: NextRequest) {
    try {
        const userId = await validateSession(request)
        if (!userId) {
            return NextResponse.json({ ok: false, message: 'Unauthorized' }, { status: 401 })
        }

        const body = await request.json().catch(() => ({}))
        const settings = assertValidSettingPayload(
            Array.isArray(body?.settings) ? body.settings : []
        )
        const desktopNotificationEnabled = Boolean(body?.desktopNotificationEnabled)

        const db = await getDb()

        await db.run(
            `INSERT OR REPLACE INTO user_notification_settings (notification_setting_id, user_id, push_enabled, record_enabled)
             VALUES (?, ?, ?, 0)`,
            [DESKTOP_NOTIFICATION_SETTING_ID, userId, desktopNotificationEnabled ? 1 : 0]
        )

        for (const setting of settings) {
            await db.run(
                `INSERT OR REPLACE INTO user_notification_settings (notification_setting_id, user_id, push_enabled, record_enabled)
                 VALUES (?, ?, ?, ?)`,
                [
                    setting.id,
                    userId,
                    setting.pushEnabled ? 1 : 0,
                    setting.recordEnabled ? 1 : 0,
                ]
            )
        }

        return NextResponse.json({ ok: true })
    } catch (error: unknown) {
        console.error('Failed to save notification settings:', error)
        return NextResponse.json(
            {
                ok: false,
                message: error instanceof Error ? error.message : 'Failed to save notification settings',
            },
            { status: 500 }
        )
    }
}
