import { PrismaClient } from '../prisma/client-generated'

const prisma = new PrismaClient()

async function main() {
    // 1. Get a user
    const user = await prisma.user.findFirst()
    if (!user) {
        console.log('No user found in database.')
        return
    }
    console.log(`Checking for User ID: ${user.id} (${user.email})`)

    // 2. Simulate logic from app/actions/notes.ts
    const sevenDaysAgo = new Date()
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
    sevenDaysAgo.setHours(0, 0, 0, 0)

    console.log(`Filtering for notes updated after: ${sevenDaysAgo.toISOString()}`)

    // 3. Query Raw
    const allNotes = await prisma.note.findMany({
        where: { userId: user.id },
        select: { id: true, title: true, contentUpdatedAt: true, updatedAt: true, dismissedFromRecent: true, isArchived: true }
    })

    console.log(`\nTotal Notes for User: ${allNotes.length}`)

    // 4. Check "Recent" candidates
    const recentCandidates = allNotes.filter(n => {
        const noteDate = new Date(n.contentUpdatedAt)
        return noteDate >= sevenDaysAgo
    })

    console.log(`Notes passing date filter: ${recentCandidates.length}`)
    recentCandidates.forEach(n => {
        console.log(` - [${n.title}] Updated: ${n.contentUpdatedAt.toISOString()} | Dismissed: ${n.dismissedFromRecent} | Archived: ${n.isArchived}`)
    })

    // 5. Check what the actual query returns
    const actualQuery = await prisma.note.findMany({
        where: {
            userId: user.id,
            contentUpdatedAt: { gte: sevenDaysAgo },
            isArchived: false,
            dismissedFromRecent: false
        },
        orderBy: { contentUpdatedAt: 'desc' },
        take: 3
    })

    console.log(`\nActual Query Returns: ${actualQuery.length} notes`)
    actualQuery.forEach(n => {
        console.log(` -> [${n.title}]`)
    })
}

main()
    .catch(e => console.error(e))
    .finally(async () => await prisma.$disconnect())
