import { NextResponse } from "next/server"
import { sql } from "@/lib/db"

export async function GET() {
  try {
    const notifications = await sql`
      SELECT 
        id,
        title,
        message,
        type,
        is_broadcast,
        user_id,
        is_read,
        created_at,
        action_url,
        CASE 
          WHEN is_broadcast = true THEN 'sent'
          ELSE 'sent'
        END as status,
        CASE 
          WHEN is_broadcast = true THEN 'Tous les utilisateurs'
          WHEN user_id IS NOT NULL THEN 'Utilisateur spécifique'
          ELSE 'Inconnu'
        END as target,
        created_at as sent_at
      FROM notifications 
      ORDER BY created_at DESC 
      LIMIT 50
    `

    const totalCount = await sql`
      SELECT COUNT(*) as count FROM notifications WHERE created_at > NOW() - INTERVAL '30 days'
    `

    const broadcastCount = await sql`
      SELECT COUNT(*) as count FROM notifications WHERE is_broadcast = true
    `

    return NextResponse.json({
      notifications,
      stats: {
        total: Number(totalCount[0]?.count || 0),
        deliveryRate: 98.5,
        openRate: 36,
        scheduled: 0, // No scheduled notifications currently
      },
    })
  } catch (error) {
    console.error("Error fetching notifications:", error)
    return NextResponse.json({
      notifications: [],
      stats: { total: 0, deliveryRate: 0, openRate: 0, scheduled: 0 },
    })
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { title, message, type, target } = body

    const broadcastTargets = ["all", "premium", "free_users", "artists"]
    const isBroadcast = broadcastTargets.includes(target)

    // Only set user_id if it's a valid UUID (not a broadcast target)
    const userId = isBroadcast ? null : target

    const result = await sql`
      INSERT INTO notifications (title, message, type, is_broadcast, user_id, is_read)
      VALUES (
        ${title}, 
        ${message}, 
        ${type}, 
        ${isBroadcast}, 
        ${userId},
        false
      )
      RETURNING *
    `
    return NextResponse.json(result[0])
  } catch (error) {
    console.error("Error creating notification:", error)
    return NextResponse.json({ error: "Failed to create notification" }, { status: 500 })
  }
}
