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

from odoo.addons.xeno_attendance.models.hr_business_trip import TRIP_TYPES


class HrBusinessTripWizard(models.TransientModel):
    """HR-only: create Business Trip requests for one or more employees at
    once. Unlike the employee self-service flow (Draft -> Submit -> Pending
    HR -> Acknowledged), each request created here goes straight to
    Acknowledged -- HR is authoring it directly, not reviewing an
    employee's own submission -- via hr.business.trip's own action_submit()/
    action_acknowledge() (not a raw state write), so the exact same
    validation and chatter trail apply. One hr.business.trip record per
    selected employee."""

    _name = "hr.business.trip.wizard"
    _description = "Create Business Trip requests for one or more employees"

    employee_ids = fields.Many2many("hr.employee", string="Employees", required=True)
    date_from = fields.Date(string="Start Date", required=True)
    date_to = fields.Date(string="End Date", required=True)
    trip_type = fields.Selection(TRIP_TYPES, string="Type", required=True)
    trip_type_other = fields.Char(string="Other Type")
    address = fields.Char()
    city = fields.Char()
    country_id = fields.Many2one("res.country", string="Country")
    reason = fields.Text()
    requirements_description = fields.Text(string="Requirements")
    remark = fields.Text()

    def action_create(self):
        self.ensure_one()
        if not (self.env.su or self.env.user.has_group("hr.group_hr_user")):
            raise UserError(_("Only HR can create Business Trip requests this way."))
        vals_common = {
            "date_from": self.date_from,
            "date_to": self.date_to,
            "trip_type": self.trip_type,
            "trip_type_other": self.trip_type_other,
            "address": self.address,
            "city": self.city,
            "country_id": self.country_id.id,
            "reason": self.reason,
            "requirements_description": self.requirements_description,
            "remark": self.remark,
        }
        Trip = self.env["hr.business.trip"]
        trips = Trip.browse()
        for employee in self.employee_ids:
            trip = Trip.create(dict(vals_common, employee_id=employee.id))
            trip.action_submit()
            trip.action_acknowledge()
            trips |= trip
        return {
            "type": "ir.actions.act_window",
            "name": _("Business Trips"),
            "res_model": "hr.business.trip",
            "view_mode": "list,form",
            "domain": [("id", "in", trips.ids)],
        }
