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

/// Stored as `"pending"`, `"approved"`, `"rejected"`, or `"cancelled"`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum JoinRequestStatus {
    Pending,
    Approved,
    Rejected,
    Cancelled,
}

impl std::fmt::Display for JoinRequestStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            JoinRequestStatus::Pending => write!(f, "pending"),
            JoinRequestStatus::Approved => write!(f, "approved"),
            JoinRequestStatus::Rejected => write!(f, "rejected"),
            JoinRequestStatus::Cancelled => write!(f, "cancelled"),
        }
    }
}

impl std::str::FromStr for JoinRequestStatus {
    type Err = &'static str;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "pending" => Ok(JoinRequestStatus::Pending),
            "approved" => Ok(JoinRequestStatus::Approved),
            "rejected" => Ok(JoinRequestStatus::Rejected),
            "cancelled" => Ok(JoinRequestStatus::Cancelled),
            _ => Err("unknown join request status"),
        }
    }
}

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "project_member_join_request")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i64,
    pub project: ProjectId,
    pub user: UserId,
    pub status: String,
    pub message: Option<String>,
    pub processed_by: Option<UserId>,
    pub processed_at: Option<DateTimeUtc>,
    pub reject_reason: Option<String>,
    pub created_at: DateTimeUtc,
    pub updated_at: DateTimeUtc,
}

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

impl ActiveModelBehavior for ActiveModel {}
