use sqlx::PgPool;
use uuid::Uuid;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotificationConfig {
    pub license_id: Uuid,
    pub server_name: String,
    pub discord_webhook_url: Option<String>,
    pub pushbullet_api_key: Option<String>,
}

/// Fetch the notification configuration for a license
pub async fn get_notification_config(pool: &PgPool, license_id: Uuid) -> Result<NotificationConfig> {
    // Join with licenses to get server_name and public_site_config to get webhook/pushbullet
    let row = sqlx::query!(
        r#"
        SELECT
            l.id as license_id,
            l.server_name,
            psc.discord_webhook_url,
            psc.pushbullet_api_key
        FROM licenses l
        LEFT JOIN public_site_config psc ON psc.license_id = l.id
        WHERE l.id = $1
        "#,
        license_id
    )
    .fetch_one(pool)
    .await
    .context("Failed to fetch notification config")?;

    Ok(NotificationConfig {
        license_id: row.license_id,
        server_name: row.server_name,
        discord_webhook_url: row.discord_webhook_url,
        pushbullet_api_key: row.pushbullet_api_key,
    })
}
