from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, DateTime
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from sqlalchemy.dialects.postgresql import ENUM as PG_ENUM, UUID
from app.db.base import Base
import enum

# A Python enum marad, de a Column definíciónál pontosítunk
class CompanyRole(str, enum.Enum):
    OWNER = "owner"
    MANAGER = "manager"
    DRIVER = "driver"

class Company(Base):
    __tablename__ = "companies"
    __table_args__ = {"schema": "data"}

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, nullable=False)
    tax_number = Column(String, nullable=True)
    subscription_tier = Column(String, default="free") 
    owner_id = Column(Integer, ForeignKey("data.users.id"), nullable=False)

    members = relationship("CompanyMember", back_populates="company", cascade="all, delete-orphan")
    assignments = relationship("VehicleAssignment", back_populates="company")

class CompanyMember(Base):
    __tablename__ = "company_members"
    __table_args__ = {"schema": "data"}

    id = Column(Integer, primary_key=True, index=True)
    company_id = Column(Integer, ForeignKey("data.companies.id"), nullable=False)
    user_id = Column(Integer, ForeignKey("data.users.id"), nullable=False)
    
    # JAVÍTÁS: Kifejezetten megadjuk a natív Postgres típust
    role = Column(
        PG_ENUM('owner', 'manager', 'driver', name='companyrole', schema='data', create_type=False),
        nullable=False
    )
    
    can_edit_service = Column(Boolean, default=False)
    can_see_costs = Column(Boolean, default=False)
    is_active = Column(Boolean, default=True)

    company = relationship("Company", back_populates="members")
    user = relationship("User")

class VehicleAssignment(Base):
    __tablename__ = "vehicle_assignments"
    __table_args__ = {"schema": "data"}

    id = Column(Integer, primary_key=True, index=True)
    company_id = Column(Integer, ForeignKey("data.companies.id"), nullable=False)
    vehicle_id = Column(UUID(as_uuid=True), ForeignKey("data.vehicles.id"), nullable=False)
    driver_id = Column(Integer, ForeignKey("data.users.id"), nullable=False)
    
    start_date = Column(DateTime(timezone=True), server_default=func.now())
    end_date = Column(DateTime(timezone=True), nullable=True)
    notes = Column(String, nullable=True)

    company = relationship("Company", back_populates="assignments")
    vehicle = relationship("Vehicle") # Itt már a Vehicle-re hivatkozunk
    driver = relationship("User", foreign_keys=[driver_id])