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

/// Workspace membership role. Values: "owner", "admin", "member"
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum WorkspaceRole {
    Owner,
    Admin,
    Member,
}

impl std::fmt::Display for WorkspaceRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WorkspaceRole::Owner => write!(f, "owner"),
            WorkspaceRole::Admin => write!(f, "admin"),
            WorkspaceRole::Member => write!(f, "member"),
        }
    }
}

impl std::str::FromStr for WorkspaceRole {
    type Err = &'static str;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "owner" => Ok(WorkspaceRole::Owner),
            "admin" => Ok(WorkspaceRole::Admin),
            "member" => Ok(WorkspaceRole::Member),
            _ => Err("unknown workspace role"),
        }
    }
}

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "workspace_membership")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i64,
    #[sea_orm(column_name = "workspace_id")]
    pub workspace_id: WorkspaceId,
    #[sea_orm(column_name = "user_id")]
    pub user_id: UserId,
    pub role: String,
    pub status: String,
    pub invited_by: Option<UserId>,
    pub joined_at: DateTimeUtc,
    pub invite_token: Option<String>,
    pub invite_expires_at: Option<DateTimeUtc>,
}

impl Model {
    pub fn role_enum(&self) -> Result<WorkspaceRole, &'static str> {
        self.role.parse()
    }
}

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

impl ActiveModelBehavior for ActiveModel {}
