from odoo import _, api, fields, models
from odoo.exceptions import UserError

HR_OFFICER_GROUP = "hr_holidays.group_hr_holidays_user"


class XenoLeaveHolidayDeduct(models.TransientModel):
    _name = "xeno.leave.holiday.deduct"
    _description = (
        "HR: deduct a leave day from one or more employees for a company "
        "holiday, per this company's policy that a company holiday draws "
        "down Annual Leave, falling back to Personal Leave and then "
        "Unpaid Leave if balance is insufficient -- never split across "
        "types for the same day(s), the whole deduction moves to the next "
        "tier if the current one can't cover it in full. The cascade "
        "itself lives on hr.leave (_xeno_deduct_for_company_holiday), "
        "shared with xeno_holidays' automatic hook on company-holiday "
        "creation -- this wizard is the manual, pick-your-own-employees "
        "entry point onto the same logic."
    )

    employee_ids = fields.Many2many("hr.employee", string="Employee", required=True)
    date_from = fields.Date(string="Holiday Start Date", required=True)
    date_to = fields.Date(string="Holiday End Date", required=True)
    name = fields.Text(string="Reason", default="Company holiday deduction")

    @api.onchange("date_from")
    def _onchange_date_from(self):
        if self.date_from and (not self.date_to or self.date_to < self.date_from):
            self.date_to = self.date_from

    def action_apply(self):
        self.ensure_one()
        if not self.env.user.has_group(HR_OFFICER_GROUP):
            raise UserError(_(
                "Only Time Off Officers can deduct a company holiday "
                "against an employee's leave balance."))
        if self.date_to < self.date_from:
            raise UserError(_("End date must be on or after start date."))
        self.env["hr.leave"]._xeno_deduct_for_company_holiday(
            self.employee_ids, self.date_from, self.date_to, reason=self.name)
        return {"type": "ir.actions.act_window_close"}
