"""
Organization models: Port, Company, BuoyOwnership
Used for multi-client access control and per-port default views.
"""
from sqlalchemy import Column, String, Float, Boolean, DateTime, Text
from sqlalchemy.sql import func
from database import Base


class Port(Base):
    """Geographic port / region served by this deployment."""
    __tablename__ = "ports"

    id           = Column(String, primary_key=True)
    name         = Column(String, nullable=False)
    country      = Column(String, default="Colombia")
    center_lat   = Column(Float, nullable=True)
    center_lon   = Column(Float, nullable=True)
    default_zoom = Column(Float, default=12.0)
    chart_name   = Column(String, nullable=True)   # folder under charts/, e.g. "BAHÍA_DE_CARTAGENA"
    activo       = Column(Boolean, default=True)
    creado_en    = Column(DateTime, server_default=func.now())


class Company(Base):
    """Buoy-owner company (client).  Belongs to a home port."""
    __tablename__ = "companies"

    id            = Column(String, primary_key=True)
    name          = Column(String, nullable=False)
    port_id       = Column(String, nullable=True)   # FK → ports.id
    contact_email = Column(String, nullable=True)
    contact_phone = Column(String, nullable=True)
    activa        = Column(Boolean, default=True)
    notas         = Column(Text, nullable=True)
    creado_en     = Column(DateTime, server_default=func.now())


class BuoyOwnership(Base):
    """
    Which company owns (and monitors) a given Aid/MMSI.
    A company user can see AIS/ATON real-time data only for buoys
    listed in this table under their company_id.
    """
    __tablename__ = "buoy_ownership"

    id         = Column(String, primary_key=True)
    company_id = Column(String, nullable=False)   # FK → companies.id
    aid_id     = Column(String, nullable=True)    # FK → aids.id  (nullable if aid not yet in DB)
    mmsi       = Column(String, nullable=True)    # direct MMSI reference
    notas      = Column(Text, nullable=True)
    creado_en  = Column(DateTime, server_default=func.now())
