"""
Tenant Location Model
Represents physical locations for enterprise tenants (central production, retail outlets)
"""

from sqlalchemy import Column, String, Boolean, DateTime, Float, ForeignKey, Text, Integer, JSON
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
import uuid

from shared.database.base import Base


class TenantLocation(Base):
    """TenantLocation model - represents physical locations for enterprise tenants"""
    __tablename__ = "tenant_locations"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    tenant_id = Column(UUID(as_uuid=True), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)
    
    # Location information
    name = Column(String(200), nullable=False)
    location_type = Column(String(50), nullable=False)  # central_production, retail_outlet
    address = Column(Text, nullable=False)
    city = Column(String(100), default="Madrid")
    postal_code = Column(String(10), nullable=False)
    latitude = Column(Float, nullable=True)
    longitude = Column(Float, nullable=True)
    
    # Location-specific configuration
    delivery_windows = Column(JSON, nullable=True)  # { "monday": "08:00-12:00,14:00-18:00", ... }
    capacity = Column(Integer, nullable=True)  # For production capacity in kg/day or storage capacity
    max_delivery_radius_km = Column(Float, nullable=True, default=50.0)
    
    # Operational hours
    operational_hours = Column(JSON, nullable=True)  # { "monday": "06:00-20:00", ... }
    is_active = Column(Boolean, default=True)
    
    # Contact information
    contact_person = Column(String(200), nullable=True)
    contact_phone = Column(String(20), nullable=True)
    contact_email = Column(String(255), nullable=True)
    
    # Custom delivery scheduling configuration per location
    delivery_schedule_config = Column(JSON, nullable=True)  # { "delivery_days": "Mon,Wed,Fri", "time_window": "07:00-10:00" }
    
    # Metadata
    metadata_ = Column(JSON, nullable=True)
    
    # Timestamps
    created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
    updated_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))

    # Relationships
    tenant = relationship("Tenant", back_populates="locations")
    
    def __repr__(self):
        return f"<TenantLocation(id={self.id}, tenant_id={self.tenant_id}, name={self.name}, type={self.location_type})>"