from odoo import models, fields, api


class EncoachStudentLeaveType(models.Model):
    _name = 'encoach.student.leave.type'
    _description = 'Student Leave Type'

    name = fields.Char(required=True)


class EncoachStudentLeave(models.Model):
    _name = 'encoach.student.leave'
    _description = 'Student Leave Request'
    _order = 'create_date desc'

    request_number = fields.Char(string='Request #', readonly=True, copy=False)
    student_id = fields.Many2one('op.student', required=True, ondelete='cascade')
    leave_type_id = fields.Many2one('encoach.student.leave.type', required=True, ondelete='restrict')
    start_date = fields.Date(required=True)
    end_date = fields.Date(required=True)
    duration = fields.Integer(compute='_compute_duration', store=True)
    description = fields.Text()
    state = fields.Selection([
        ('draft', 'Draft'),
        ('confirm', 'Confirmed'),
        ('approve', 'Approved'),
        ('refuse', 'Refused'),
        ('cancel', 'Cancelled'),
    ], default='draft')
    approve_date = fields.Date()
    approved_by = fields.Many2one('res.users', ondelete='set null')

    @api.depends('start_date', 'end_date')
    def _compute_duration(self):
        for rec in self:
            if rec.start_date and rec.end_date:
                rec.duration = (rec.end_date - rec.start_date).days + 1
            else:
                rec.duration = 0

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            if not vals.get('request_number'):
                vals['request_number'] = self.env['ir.sequence'].next_by_code('encoach.student.leave') or 'SL-NEW'
        return super().create(vals_list)
