# -*- coding: utf-8 -*-
# Copyright 2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)

from odoo import models, fields, api


class FusionClockPenalty(models.Model):
    _name = 'fusion.clock.penalty'
    _description = 'Clock Penalty'
    _order = 'date desc, id desc'
    _rec_name = 'display_name'

    attendance_id = fields.Many2one(
        'hr.attendance',
        string='Attendance',
        ondelete='cascade',
        index=True,
    )
    employee_id = fields.Many2one(
        'hr.employee',
        string='Employee',
        required=True,
        index=True,
    )
    penalty_type = fields.Selection(
        [
            ('late_in', 'Late Clock-In'),
            ('early_out', 'Early Clock-Out'),
        ],
        string='Penalty Type',
        required=True,
    )
    scheduled_time = fields.Datetime(string='Scheduled Time')
    actual_time = fields.Datetime(string='Actual Time')
    difference_minutes = fields.Float(
        string='Difference (min)',
        compute='_compute_difference',
        store=True,
    )
    penalty_minutes = fields.Float(
        string='Deducted (min)',
        default=0.0,
        help="Minutes deducted from worked hours as penalty.",
    )
    date = fields.Date(string='Date', required=True, index=True)
    company_id = fields.Many2one(
        'res.company',
        string='Company',
        related='employee_id.company_id',
        store=True,
    )
    note = fields.Text(string='Note')

    display_name = fields.Char(compute='_compute_display_name', store=True)

    @api.depends('scheduled_time', 'actual_time')
    def _compute_difference(self):
        for rec in self:
            if rec.scheduled_time and rec.actual_time:
                delta = abs((rec.actual_time - rec.scheduled_time).total_seconds())
                rec.difference_minutes = round(delta / 60.0, 1)
            else:
                rec.difference_minutes = 0.0

    @api.depends('employee_id', 'penalty_type', 'date')
    def _compute_display_name(self):
        labels = dict(self._fields['penalty_type'].selection)
        for rec in self:
            emp = rec.employee_id.name or ''
            ptype = labels.get(rec.penalty_type, '')
            rec.display_name = f"{emp} - {ptype} ({rec.date})" if rec.date else f"{emp} - {ptype}"
