"""Application support teams and their contacts.

A support team is who you contact about an application; each team carries an
optional ServiceNow group deep link (teamurl) and a list of named contacts
(the people you actually reach out to, legacy called them "app owners").
Applications point at one team via applications.supportteamid.
"""

from shopdb.extensions import db
from .base import BaseModel


class SupportTeam(BaseModel):
    """A support team an application belongs to."""
    __tablename__ = 'supportteams'

    supportteamid = db.Column(db.Integer, primary_key=True)
    teamname = db.Column(db.String(100), unique=True, nullable=False)
    teamurl = db.Column(db.Text)  # ServiceNow group deep link, nullable
    # Teams (or other) webhook this team receives alerts on; alerting plugins
    # route to it by selecting this team. Nullable = no webhook for this team.
    webhookurl = db.Column(db.Text)

    # Contacts cascade-delete with the team.
    contacts = db.relationship(
        'SupportTeamContact', back_populates='team',
        cascade='all, delete-orphan', lazy='select')
    applications = db.relationship(
        'Application', back_populates='supportteam', lazy='dynamic')

    def active_contacts(self):
        """Return active contacts in sortorder (then contactid) order."""
        return sorted(
            (c for c in self.contacts if c.isactive),
            key=lambda c: (c.sortorder, c.contactid or 0))

    def to_dict(self, with_contacts=True):
        """Serialize the team, nesting its active contacts by default."""
        result = super().to_dict()
        if with_contacts:
            result['contacts'] = [c.to_dict() for c in self.active_contacts()]
        return result

    def __repr__(self):
        return f"<SupportTeam {self.teamname}>"


class SupportTeamContact(BaseModel):
    """A person to contact for a support team."""
    __tablename__ = 'supportteamcontacts'

    contactid = db.Column(db.Integer, primary_key=True)
    supportteamid = db.Column(
        db.Integer,
        db.ForeignKey('supportteams.supportteamid', ondelete='CASCADE'),
        nullable=False)
    name = db.Column(db.String(100), nullable=False)
    sso = db.Column(db.String(50))
    sortorder = db.Column(db.Integer, nullable=False, default=0)

    team = db.relationship('SupportTeam', back_populates='contacts')

    def __repr__(self):
        return f"<SupportTeamContact {self.name}>"
