ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
use crate::builders::traits::{
    ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::EventBuildError;
use crate::schema::Event;
use std::collections::HashMap;

/// Builder for constructing scheduled events (pg_cron jobs)
#[derive(Debug, Clone)]
pub struct EventBuilder {
    name: Option<String>,
    schedule: Option<String>,
    command: Option<String>,
    active: bool,
    database: Option<String>,
    username: Option<String>,
    nodename: Option<String>,
    port: Option<u16>,
    parameters: HashMap<String, String>,
    comment: Option<String>,
}

impl EventBuilder {
    /// Create a new event builder
    pub fn new() -> Self {
        Self {
            name: None,
            schedule: None,
            command: None,
            active: true,
            database: None,
            username: None,
            nodename: None,
            port: None,
            parameters: HashMap::new(),
            comment: None,
        }
    }

    /// Set the event name
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the event name (mutable reference version for conditional building)
    pub fn set_name(&mut self, name: impl Into<String>) {
        self.name = Some(name.into());
    }

    /// Set the cron schedule for this event
    pub fn schedule(mut self, schedule: impl Into<String>) -> Self {
        self.schedule = Some(schedule.into());
        self
    }

    /// Set the schedule (mutable reference version for conditional building)
    pub fn set_schedule(&mut self, schedule: impl Into<String>) {
        self.schedule = Some(schedule.into());
    }

    /// Set the command to execute
    pub fn command(mut self, command: impl Into<String>) -> Self {
        self.command = Some(command.into());
        self
    }

    /// Set the command (mutable reference version for conditional building)
    pub fn set_command(&mut self, command: impl Into<String>) {
        self.command = Some(command.into());
    }

    /// Set whether this event is active
    pub fn active(mut self, active: bool) -> Self {
        self.active = active;
        self
    }

    /// Set active status (mutable reference version for conditional building)
    pub fn set_active(&mut self, active: bool) {
        self.active = active;
    }

    /// Set the database to connect to
    pub fn database(mut self, database: impl Into<String>) -> Self {
        self.database = Some(database.into());
        self
    }

    /// Set the database (mutable reference version for conditional building)
    pub fn set_database(&mut self, database: impl Into<String>) {
        self.database = Some(database.into());
    }

    /// Set the username to connect as
    pub fn username(mut self, username: impl Into<String>) -> Self {
        self.username = Some(username.into());
        self
    }

    /// Set the username (mutable reference version for conditional building)
    pub fn set_username(&mut self, username: impl Into<String>) {
        self.username = Some(username.into());
    }

    /// Set the node name (hostname) to connect to
    pub fn nodename(mut self, nodename: impl Into<String>) -> Self {
        self.nodename = Some(nodename.into());
        self
    }

    /// Set the node name (mutable reference version for conditional building)
    pub fn set_nodename(&mut self, nodename: impl Into<String>) {
        self.nodename = Some(nodename.into());
    }

    /// Set the port to connect to
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    /// Set the port (mutable reference version for conditional building)
    pub fn set_port(&mut self, port: u16) {
        self.port = Some(port);
    }

    /// Add a parameter to the event
    pub fn parameter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.parameters.insert(key.into(), value.into());
        self
    }

    /// Add a parameter (mutable reference version for conditional building)
    pub fn add_parameter(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.parameters.insert(key.into(), value.into());
    }

    /// Add multiple parameters to the event
    pub fn parameters(mut self, parameters: HashMap<String, String>) -> Self {
        self.parameters.extend(parameters);
        self
    }

    /// Add multiple parameters (mutable reference version for conditional building)
    pub fn add_parameters(&mut self, parameters: HashMap<String, String>) {
        self.parameters.extend(parameters);
    }

    /// Set a comment for this event
    pub fn comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }

    /// Set comment (mutable reference version for conditional building)
    pub fn set_comment(&mut self, comment: impl Into<String>) {
        self.comment = Some(comment.into());
    }

    /// Convenience method for daily schedule at specific time
    pub fn daily_at(mut self, hour: u8, minute: u8) -> Self {
        if hour > 23 || minute > 59 {
            return self; // Invalid time, keep existing schedule
        }
        self.schedule = Some(format!("{} {} * * *", minute, hour));
        self
    }

    /// Convenience method for weekly schedule
    pub fn weekly(mut self, day_of_week: u8, hour: u8, minute: u8) -> Self {
        if day_of_week > 6 || hour > 23 || minute > 59 {
            return self; // Invalid time, keep existing schedule
        }
        self.schedule = Some(format!("{} {} * * {}", minute, hour, day_of_week));
        self
    }

    /// Convenience method for monthly schedule
    pub fn monthly(mut self, day_of_month: u8, hour: u8, minute: u8) -> Self {
        if day_of_month > 31 || hour > 23 || minute > 59 {
            return self; // Invalid time, keep existing schedule
        }
        self.schedule = Some(format!("{} {} {} * *", minute, hour, day_of_month));
        self
    }

    /// Convenience method for hourly schedule
    pub fn hourly(mut self, minute: u8) -> Self {
        if minute > 59 {
            return self; // Invalid minute, keep existing schedule
        }
        self.schedule = Some(format!("{} * * * *", minute));
        self
    }

    /// Convenience method for every N minutes
    pub fn every_minutes(mut self, minutes: u8) -> Self {
        if minutes == 0 || minutes > 59 {
            return self; // Invalid interval, keep existing schedule
        }
        self.schedule = Some(format!("*/{} * * * *", minutes));
        self
    }

    /// Convenience method for every N hours
    pub fn every_hours(mut self, hours: u8) -> Self {
        if hours == 0 || hours > 23 {
            return self; // Invalid interval, keep existing schedule
        }
        self.schedule = Some(format!("0 */{} * * *", hours));
        self
    }
}

impl SchemaBuilder for EventBuilder {
    type Output = Event;
    type Error = EventBuildError;

    fn build(self) -> Result<Self::Output, EventBuildError> {
        let name = self.name.ok_or(EventBuildError::MissingName)?;
        let schedule = self.schedule.ok_or(EventBuildError::MissingSchedule)?;
        let command = self.command.ok_or(EventBuildError::MissingCommand)?;

        let mut event = Event::new(name, schedule, command);

        event.enabled = self.active;

        if let Some(database) = self.database {
            event.database = Some(database);
        }

        if let Some(username) = self.username {
            event.username = Some(username);
        }

        Ok(event)
    }
}

impl ValidatableBuilder for EventBuilder {
    fn is_valid(&self) -> bool {
        self.name.is_some()
            && self.schedule.is_some()
            && self.command.is_some()
            && self.port.map_or(true, |port| port > 0)
    }

    fn validation_errors(&self) -> Vec<String> {
        let mut errors = Vec::new();

        if self.name.is_none() {
            errors.push("Event name is required".to_string());
        }

        if self.schedule.is_none() {
            errors.push("Event schedule is required".to_string());
        }

        if self.command.is_none() {
            errors.push("Event command is required".to_string());
        }

        // Validate cron schedule format (basic validation)
        if let Some(ref schedule) = self.schedule {
            let parts: Vec<&str> = schedule.split_whitespace().collect();
            if parts.len() != 5 {
                errors.push("Invalid cron schedule format".to_string());
            }
        }

        // Validate port if specified
        if let Some(port) = self.port {
            if port == 0 {
                errors.push(format!("Invalid port number: {}", port));
            }
        }

        errors
    }
}

impl ConditionalBuilder for EventBuilder {
    // The trait provides default implementations for when() and when_else()
    // No additional implementation needed
}

impl InspectableBuilder for EventBuilder {
    fn debug_info(&self) -> String {
        format!(
            "EventBuilder {{ name: {:?}, schedule: {:?}, command: {:?}, active: {}, database: {:?}, username: {:?}, nodename: {:?}, port: {:?}, parameters: {:?}, comment: {:?} }}",
            self.name,
            self.schedule,
            self.command,
            self.active,
            self.database,
            self.username,
            self.nodename,
            self.port,
            self.parameters,
            self.comment
        )
    }

    fn summary(&self) -> String {
        let name = self.name.as_deref().unwrap_or("unnamed");
        let schedule = self.schedule.as_deref().unwrap_or("no schedule");
        let status = if self.active { "active" } else { "inactive" };

        format!("Event '{}' scheduled '{}' ({})", name, schedule, status)
    }
}