use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use uuid::Uuid;

use super::{AddressFields, BaseFields, ContactFields, EntityStatus};

/// Top-level business entity
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct Customer {
    #[sqlx(flatten)]
    #[serde(flatten)]
    pub base: BaseFields,
    pub name: String,
    pub status: EntityStatus,
    pub start_date: Option<NaiveDate>,
    pub end_date: Option<NaiveDate>,
    pub billing_terms: Option<String>,
    pub billing_email: Option<String>,
    pub wave_customer_id: Option<String>,
}

impl Customer {
    /// Check if customer is currently active based on dates
    pub fn is_active(&self) -> bool {
        if self.status != EntityStatus::Active {
            return false;
        }

        let today = chrono::Utc::now().date_naive();

        if let Some(start) = self.start_date {
            if today < start {
                return false;
            }
        }

        if let Some(end) = self.end_date {
            if today > end {
                return false;
            }
        }

        true
    }
}

/// Customer address (for customers without accounts)
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct CustomerAddress {
    #[sqlx(flatten)]
    #[serde(flatten)]
    pub base: BaseFields,
    pub customer_id: Uuid,
    #[sqlx(flatten)]
    #[serde(flatten)]
    pub address: AddressFields,
    pub is_active: bool,
    pub is_primary: bool,
    pub name: Option<String>,
    pub notes: Option<String>,
}

/// Customer contact
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct CustomerContact {
    #[sqlx(flatten)]
    #[serde(flatten)]
    pub base: BaseFields,
    pub customer_id: Uuid,
    #[sqlx(flatten)]
    #[serde(flatten)]
    pub contact: ContactFields,
    pub email: Option<String>,
    pub is_active: bool,
    pub is_primary: bool,
    pub notes: Option<String>,
}

impl CustomerContact {
    pub fn full_name(&self) -> String {
        self.contact.full_name()
    }
}
