use crate::{DateTimeUtc, ProjectId, UserId};
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};

/// Audit action types, stored as strings like `"create"`, `"update"`, `"delete"`, `"transfer"`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum AuditAction {
    Create,
    Update,
    Delete,
    Transfer,
    Rename,
    SettingsChange,
}

impl std::fmt::Display for AuditAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AuditAction::Create => write!(f, "create"),
            AuditAction::Update => write!(f, "update"),
            AuditAction::Delete => write!(f, "delete"),
            AuditAction::Transfer => write!(f, "transfer"),
            AuditAction::Rename => write!(f, "rename"),
            AuditAction::SettingsChange => write!(f, "settings_change"),
        }
    }
}

impl std::str::FromStr for AuditAction {
    type Err = &'static str;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "create" => Ok(AuditAction::Create),
            "update" => Ok(AuditAction::Update),
            "delete" => Ok(AuditAction::Delete),
            "transfer" => Ok(AuditAction::Transfer),
            "rename" => Ok(AuditAction::Rename),
            "settings_change" => Ok(AuditAction::SettingsChange),
            _ => Err("unknown audit action"),
        }
    }
}

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "project_audit_log")]
pub struct Model {
    #[sea_orm(primary_key, auto_increment = true)]
    pub id: i64,
    pub project: ProjectId,
    pub actor: UserId,
    #[sea_orm(column_type = "Text")]
    pub action: String,
    #[sea_orm(column_type = "JsonBinary", nullable)]
    pub details: Option<Json>,
    pub ip_address: Option<String>,
    pub user_agent: Option<String>,
    pub created_at: DateTimeUtc,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}
