from odoo import models, fields


class EncoachInvite(models.Model):
    _name = "encoach.invite"
    _description = "EnCoach Entity Invite"

    from_user_id = fields.Many2one("res.users", required=True, ondelete="cascade")
    to_user_id = fields.Many2one("res.users", required=True, ondelete="cascade")
    entity_id = fields.Many2one("encoach.entity", required=True, ondelete="cascade")
    status = fields.Selection(
        [
            ("pending", "Pending"),
            ("accepted", "Accepted"),
            ("declined", "Declined"),
        ],
        default="pending",
    )
    legacy_id = fields.Char(index=True)

    def action_accept(self):
        self.ensure_one()
        self.status = "accepted"
        existing = self.env["encoach.user.entity.rel"].search([
            ("user_id", "=", self.to_user_id.id),
            ("entity_id", "=", self.entity_id.id),
        ], limit=1)
        if not existing:
            self.env["encoach.user.entity.rel"].create({
                "user_id": self.to_user_id.id,
                "entity_id": self.entity_id.id,
            })

    def action_decline(self):
        self.ensure_one()
        self.status = "declined"

    def to_encoach_dict(self):
        self.ensure_one()
        return {
            "id": self.id,
            "from": self.from_user_id.id,
            "to": self.to_user_id.id,
            "entity": self.entity_id.id,
            "status": self.status,
        }
