from datetime import date

from pydantic import BaseModel, Field, field_validator, model_validator
from src.__types.index import Distribution, Unit
from src.domain.entities.quota_allocation import QuotaAllocationType


class ContractEvent(BaseModel):
    """契約イベント

    ContractProviderから提供される、契約の詳細情報
    """

    legal_name: str = Field(..., description="会社名")
    distribution: Distribution = Field(..., description="商流")
    customer_id: str = Field(..., description="取引先ID")
    contract_id: str = Field(..., description="見積書番号")
    type: QuotaAllocationType = Field(..., description="契約タイプ（自動更新 / 随時拡張）")
    amount: Unit = Field(..., description="追加ユニット数")
    valid_from_date: date = Field(..., description="契約開始日")
    valid_to_date: date = Field(..., description="契約終了日")

    @field_validator("valid_from_date", "valid_to_date", mode="before")
    @classmethod
    def parse_date(cls, value: str | date) -> date:
        if isinstance(value, date):
            return value
        return date.fromisoformat(value)

    @model_validator(mode="after")
    def validate_dates(self) -> "ContractEvent":
        """有効開始日と有効終了日の整合性を確認する"""
        if self.valid_from_date >= self.valid_to_date:
            raise ValueError("valid_from_date must be before valid_to_date")
        return self
