// SPDX-FileCopyrightText: 2026 Contributors to brew-proxy <https://codeberg.org/HastD/brew-proxy>
//
// SPDX-License-Identifier: Apache-2.0 OR MIT

use std::{process::ExitCode, time::Duration};

use async_trait::async_trait;
use tracing::{error, info};
use tracing_subscriber::EnvFilter;
use zbus::{Connection, fdo};
use zbus_polkit::policykit1::Subject;

use brew_proxy::daemon;
use brew_proxy_utils::{BrewCommand, BrewCommandLine, BusType, PolkitAction};

/// Mock authorization checker that accepts Info actions and denies everything else
struct MockAuth;

#[async_trait]
impl daemon::AuthChecker for MockAuth {
    async fn check_authorization(
        &self,
        _conn: &Connection,
        _subject: &Subject,
        cmdline: BrewCommandLine<'_>,
        interactive: bool,
    ) -> fdo::Result<()> {
        let action = PolkitAction::from(cmdline);
        if matches!(action, PolkitAction::Info) || matches!(cmdline.command, BrewCommand::Bundle) {
            Ok(())
        } else if interactive {
            Err(fdo::Error::AccessDenied("mock auth prompt".to_owned()))
        } else {
            Err(fdo::Error::AccessDenied(
                "mock auth denial (noninteractive)".to_owned(),
            ))
        }
    }
}

#[tokio::main]
async fn main() -> ExitCode {
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .with_writer(std::io::stderr)
        .init();
    info!("brew-proxy-daemon [TEST VERSION]");

    let idle_timeout = if let Some(Ok(millis)) = std::env::args().nth(1).map(|s| s.parse::<u64>()) {
        Duration::from_millis(millis)
    } else {
        Duration::from_secs(30)
    };

    let mock_auth = Box::new(MockAuth);
    if let Err(err) = daemon::run_with_idle_timeout(
        "./tests/mock-brew.sh".into(),
        BusType::Session,
        mock_auth,
        idle_timeout,
    )
    .await
    {
        error!("{err}");
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}
