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

/// Stored as `"create"`, `"read"`, `"update"`, `"delete"`, `"transfer"` etc.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum AccessAction {
    Create,
    Read,
    Update,
    Delete,
    Transfer,
    Invite,
    RemoveMember,
}

impl std::fmt::Display for AccessAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AccessAction::Create => write!(f, "create"),
            AccessAction::Read => write!(f, "read"),
            AccessAction::Update => write!(f, "update"),
            AccessAction::Delete => write!(f, "delete"),
            AccessAction::Transfer => write!(f, "transfer"),
            AccessAction::Invite => write!(f, "invite"),
            AccessAction::RemoveMember => write!(f, "remove_member"),
        }
    }
}

impl std::str::FromStr for AccessAction {
    type Err = &'static str;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "create" => Ok(AccessAction::Create),
            "read" => Ok(AccessAction::Read),
            "update" => Ok(AccessAction::Update),
            "delete" => Ok(AccessAction::Delete),
            "transfer" => Ok(AccessAction::Transfer),
            "invite" => Ok(AccessAction::Invite),
            "remove_member" => Ok(AccessAction::RemoveMember),
            _ => Err("unknown access action"),
        }
    }
}

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "project_access_log")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i64,
    pub project: ProjectId,
    pub actor_uid: Option<UserId>,
    pub action: String,
    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 {}
