package models

import "odoo-go/pkg/orm"

// initHrAttendance registers the hr.attendance model.
// Mirrors: odoo/addons/hr_attendance/models/hr_attendance.py
func initHrAttendance() {
	m := orm.NewModel("hr.attendance", orm.ModelOpts{
		Description: "Attendance",
		Order:       "check_in desc",
	})
	m.AddFields(
		orm.Many2one("employee_id", "hr.employee", orm.FieldOpts{String: "Employee", Required: true}),
		orm.Datetime("check_in", orm.FieldOpts{String: "Check In", Required: true}),
		orm.Datetime("check_out", orm.FieldOpts{String: "Check Out"}),
		orm.Float("worked_hours", orm.FieldOpts{String: "Worked Hours", Compute: "_compute_worked_hours", Store: true}),
		orm.Many2one("company_id", "res.company", orm.FieldOpts{String: "Company"}),
	)

	m.RegisterCompute("worked_hours", func(rs *orm.Recordset) (orm.Values, error) {
		env := rs.Env()
		attID := rs.IDs()[0]
		var hours float64
		env.Tx().QueryRow(env.Ctx(),
			`SELECT COALESCE(EXTRACT(EPOCH FROM (check_out - check_in)) / 3600.0, 0)
             FROM hr_attendance WHERE id = $1 AND check_out IS NOT NULL`, attID,
		).Scan(&hours)
		return orm.Values{"worked_hours": hours}, nil
	})
}
