//! Project creation handler - creates project in database

use crate::ui_config;
use anyhow::{anyhow, Context, Result};
use chrono::Utc;
use colored::Colorize;
use std::path::Path;
use syntaxis_core::persistence::{Database, DbProject, SqliteDatabase};
use syntaxis_core::ProjectConfig;
use tools_shared::find_config_path_warn_conflicts;
use uuid::Uuid;

/// Handler for project creation
#[derive(Debug)]
pub struct CreateHandler;

impl CreateHandler {
    /// Create project in database from TOML configuration
    pub async fn create_project() -> Result<()> {
        println!("📦 Creating project in database\n");

        // Load configuration from discovered path
        let config_path = Self::find_config()?;
        let config = ProjectConfig::load_from_file(&config_path)
            .context("Failed to load project configuration")?;

        // Config directory is the parent of the config file
        let config_dir = config_path
            .parent()
            .unwrap_or_else(|| Path::new(".project"));

        println!(
            "  {} Loading configuration from: {}",
            "•".cyan(),
            config_path.display()
        );
        println!("  Project name: {}", config.project.name.bold());
        println!("  Version: {}", config.project.version);

        // Initialize database
        println!("\n  {} Initializing database...", "•".cyan());
        // Database path is relative to config directory
        let db_path = config_dir.join(&config.database_path);

        // Ensure we have an absolute path for database initialization
        let db_path_str = db_path
            .canonicalize()
            .unwrap_or_else(|_| db_path.clone())
            .to_string_lossy()
            .to_string();

        let db = SqliteDatabase::new(&db_path_str)
            .await
            .context("Failed to initialize database")?;

        // Create project entry in database
        println!("  {} Creating project entity...", "•".cyan());
        let now = Utc::now().to_rfc3339();
        let project = DbProject {
            id: Uuid::new_v4().to_string(),
            name: config.project.name.clone(),
            version: config.project.version.clone(),
            description: config.project.description.clone(),
            project_type: format!("{:?}", config.project_type),
            current_phase: "Creation".to_string(),
            created_at: now.clone(),
            updated_at: now,
        };
        db.create_project(&project)
            .await
            .context("Failed to create project in database")?;

        println!("\n✅ Project created successfully!");
        println!("  Name: {}", config.project.name.green().bold());
        println!("  Version: {}", config.project.version);
        println!("  Database: {}", db_path.display());
        println!("  Status: {} (ready to use)", "Active".green());

        println!("\n  Next steps:");
        let app_name = ui_config::get_app_name();
        println!("    • {} phase current", app_name);
        println!("    • {} checklist add '<description>'", app_name);
        println!("    • {} security profile <type>", app_name);

        Ok(())
    }

    // Helper: Find config file using tools-shared
    fn find_config() -> Result<std::path::PathBuf> {
        let app_name = ui_config::get_app_name();
        find_config_path_warn_conflicts("config.toml", None).ok_or_else(|| {
            anyhow!(
                "Configuration not found. Please run 'init' first:\n\
                 - {} init\n\
                 - {} create",
                app_name,
                app_name
            )
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_create_handler_creation() {
        let handler = CreateHandler;
        assert_eq!(format!("{:?}", handler), "CreateHandler");
    }
}
