"""Extend hr.department with SAP B1 linkage (Department code)."""
from odoo import fields, models


class HrDepartment(models.Model):
    _inherit = "hr.department"

    b1_dept_code = fields.Integer(
        string="SAP B1 Department Code", index=True, copy=False,
        help="Code of the linked Department in SAP Business One.",
    )

    def _b1_get_or_create(self, code, name):
        """Return the hr.department for a B1 department code, creating it if new."""
        if not code:
            return self.browse()
        dept = self.with_context(active_test=False).search(
            [("b1_dept_code", "=", code)], limit=1
        )
        if not dept and name:
            dept = self.with_context(active_test=False).search(
                [("name", "=", name), ("b1_dept_code", "=", False)], limit=1
            )
        if dept:
            if not dept.b1_dept_code:
                dept.b1_dept_code = code
            return dept
        return self.create({"name": name or f"B1 Dept {code}", "b1_dept_code": code})
