import { NextRequest, NextResponse } from 'next/server'
import { getDb } from '@/server/db'

export async function GET(request: NextRequest) {
    try {
        const db = await getDb()
        const notices = await db.all<{
            id: string
            title: string
            content: string
            url: string
            category: string
            createdAt: string
        }>( 
            `SELECT notice_id AS id, title, content, redirect_url AS url, category,
                    CASE WHEN created_at > 0 THEN datetime(created_at, 'unixepoch') ELSE '' END AS createdAt
             FROM system_notices
             ORDER BY created_at DESC
             LIMIT 50`
        )
        return NextResponse.json({
            ok: true,
            notices: notices.map((n) => ({
                id: n.id,
                title: n.title,
                content: n.content,
                url: n.url,
                category: n.category || 'general',
                date: n.createdAt,
            })),
        })
    } catch (error: any) {
        console.error('Failed to fetch notices:', error)
        return NextResponse.json(
            { ok: false, message: error?.message || 'Failed to fetch notices' },
            { status: 500 }
        )
    }
}

