"""
PM Module — Resource Entities

منابع پروژه — انسانی، تجهیزات، مواد.
"""

from dataclasses import dataclass, field
from datetime import date
from decimal import Decimal
from typing import Optional
from uuid import UUID, uuid4

from shared.base_classes.entity import TenantEntity

from ..value_objects.common import ResourceType


@dataclass
class Resource(TenantEntity):
    """
    منبع پروژه.

    یکپارچه‌سازی:
    - employee_id → UUID مرجع به Employee (HRM) — بدون FK مستقیم
    - user_id → FK به User (پلتفرم)
    - company_id → FK به Company (پلتفرم)
    """

    name: str = ""
    code: str = ""
    resource_type: ResourceType = ResourceType.HUMAN

    # --- Integration ---
    employee_id: Optional[UUID] = None    # → HRM Employee (UUID only)
    user_id: Optional[UUID] = None        # → User (platform)
    company_id: Optional[UUID] = None     # → Company (platform)

    # --- Rates ---
    standard_rate: Decimal = Decimal("0")
    overtime_rate: Decimal = Decimal("0")
    cost_per_use: Decimal = Decimal("0")
    currency_id: Optional[UUID] = None    # → Currency (platform)

    # --- Capacity ---
    max_units: Decimal = Decimal("100")   # درصد — ۱۰۰ = تمام وقت
    calendar_id: Optional[UUID] = None    # → Calendar

    # --- Contact ---
    email: str = ""
    phone: str = ""

    # --- Status ---
    is_active: bool = True
    notes: str = ""
    metadata: Optional[dict] = field(default_factory=dict)


@dataclass
class ResourceAssignment(TenantEntity):
    """
    تخصیص منبع به تسک.
    """

    project_id: UUID = field(default_factory=uuid4)
    task_id: UUID = field(default_factory=uuid4)
    resource_id: UUID = field(default_factory=uuid4)

    # --- Allocation ---
    units: Decimal = Decimal("100")        # درصد تخصیص
    planned_hours: Decimal = Decimal("0")
    actual_hours: Decimal = Decimal("0")

    # --- Cost ---
    planned_cost: Decimal = Decimal("0")
    actual_cost: Decimal = Decimal("0")

    # --- Dates ---
    start_date: Optional[date] = None
    end_date: Optional[date] = None

    # --- Status ---
    is_active: bool = True
    notes: str = ""

    @property
    def remaining_hours(self) -> Decimal:
        return max(self.planned_hours - self.actual_hours, Decimal("0"))

    @property
    def cost_variance(self) -> Decimal:
        return self.planned_cost - self.actual_cost
