from odoo import api, fields, models


class EncoachLmsBranch(models.Model):
    _name = "encoach.lms.branch"
    _description = "EnCoach LMS Branch"
    _order = "name asc, id asc"

    name = fields.Char(required=True)
    code = fields.Char(index=True)
    active = fields.Boolean(default=True)
    entity_id = fields.Many2one(
        "encoach.entity",
        required=True,
        ondelete="cascade",
        index=True,
        string="Entity",
    )
    notes = fields.Text()

    course_ids = fields.One2many("op.course", "branch_id")
    batch_ids = fields.One2many("op.batch", "branch_id")
    student_ids = fields.One2many("op.student", "branch_id")
    teacher_ids = fields.One2many("op.faculty", "branch_id")

    course_count = fields.Integer(compute="_compute_counts")
    batch_count = fields.Integer(compute="_compute_counts")
    student_count = fields.Integer(compute="_compute_counts")
    teacher_count = fields.Integer(compute="_compute_counts")

    _sql_constraints = [
        ("branch_entity_code_uniq", "unique(entity_id, code)", "Branch code must be unique per entity."),
    ]

    @api.depends("course_ids", "batch_ids", "student_ids", "teacher_ids")
    def _compute_counts(self):
        for rec in self:
            rec.course_count = len(rec.course_ids)
            rec.batch_count = len(rec.batch_ids)
            rec.student_count = len(rec.student_ids)
            rec.teacher_count = len(rec.teacher_ids)

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            if not vals.get("code") and vals.get("name"):
                vals["code"] = vals["name"].upper().replace(" ", "_")[:24]
        return super().create(vals_list)

