// Copyright 2024 bmc::labs GmbH. All rights reserved.

mod date_time;
mod executors;
mod runner_token;
mod url;

pub use date_time::DateTime;
pub use executors::{Docker, Executor, PullPolicy, SecurityOpt, Service, Sysctls};
pub use runner_token::{RunnerToken, RunnerTokenParseError};
use serde::Serialize;
pub use url::Url;

/// Defines one runner.
///
/// See the [`Default` implementation](Self::default) for the default values.
///
/// Further documentation found in [the GitLab
/// docs](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runners-section).
#[derive(Debug, Serialize)]
pub struct Runner {
    pub id: u32,
    pub name: String,
    pub url: Url,
    pub token: RunnerToken,
    /// Timestamp of when the token was "obtained". This field is undocumented in [the GitLab docs
    /// for the GitLab Runners configuration
    /// file](https://docs.gitlab.com/runner/configuration/advanced-configuration.html) and it is
    /// nowhere to be found in [the GitLab API docs](https://docs.gitlab.com/ee/api/runners.html),
    /// but it is present in the configuration files generated by the `gitlab-runner` binary. It's
    /// the timestamp of when the token was first handed to the service processing it (and using
    /// this library).
    pub token_obtained_at: DateTime,
    /// Timestamp of when the token will "expire". While being undocumented in the GitLab Runner
    /// docs for the configuration file, it can be obtained through [the GitLab
    /// API](https://docs.gitlab.com/ee/api/runners.html#verify-authentication-for-a-registered-runner)
    /// and can be set here.
    pub token_expires_at: DateTime,
    pub limit: u32,
    #[serde(flatten)]
    pub executor: Executor,
    pub builds_dir: String,
    pub cache_dir: String,
    /// Used to set environment variables for a runner or job. Example: `["FOO=bar", "BAZ=qux"]`
    pub environment: Vec<String>,
    pub request_concurrency: u32,
    pub output_limit: u32,
}

impl Default for Runner {
    fn default() -> Self {
        Self {
            id: 1,
            name: "default".to_string(),
            url: Url::parse("https://gitlab.com/").expect("given string is a URL"),
            token: RunnerToken::parse("glrt-0123456789_abcdefXYZ")
                .expect("given string is a valid token"),
            token_obtained_at: DateTime::now(),
            token_expires_at: DateTime::parse("0001-01-01T00:00:00Z")
                .expect("given string is a valid ISO8601 timestamp"),
            limit: 0,
            executor: Executor::Docker {
                docker: Default::default(),
            },
            builds_dir: "".to_string(),
            cache_dir: "".to_string(),
            environment: vec![],
            request_concurrency: 1,
            output_limit: 4096,
        }
    }
}
