package models

import (
	"fmt"
	"time"

	"odoo-go/pkg/orm"
)

// initProjectUpdate registers the project.update model.
// Mirrors: odoo/addons/project/models/project_update.py
//
//	class ProjectUpdate(models.Model):
//	    _name = 'project.update'
//	    _description = 'Project Update'
//	    _order = 'date desc'
func initProjectUpdate() {
	m := orm.NewModel("project.update", orm.ModelOpts{
		Description: "Project Update",
		Order:       "date desc, id desc",
	})

	m.AddFields(
		orm.Many2one("project_id", "project.project", orm.FieldOpts{
			String: "Project", Required: true, OnDelete: orm.OnDeleteCascade, Index: true,
		}),
		orm.Char("name", orm.FieldOpts{String: "Title", Required: true}),
		orm.Selection("status", []orm.SelectionItem{
			{Value: "on_track", Label: "On Track"},
			{Value: "at_risk", Label: "At Risk"},
			{Value: "off_track", Label: "Off Track"},
			{Value: "on_hold", Label: "On Hold"},
		}, orm.FieldOpts{String: "Status", Required: true, Default: "on_track"}),
		orm.Date("date", orm.FieldOpts{String: "Date", Required: true}),
		orm.HTML("description", orm.FieldOpts{String: "Description"}),
		orm.Many2one("user_id", "res.users", orm.FieldOpts{String: "Author"}),
		orm.Float("progress", orm.FieldOpts{String: "Progress (%)"}),
		orm.Integer("color", orm.FieldOpts{String: "Color Index"}),
	)

	// DefaultGet: set date to today, user to current user
	m.DefaultGet = func(env *orm.Environment, fields []string) orm.Values {
		vals := make(orm.Values)
		vals["date"] = time.Now().Format("2006-01-02")
		if env.UID() > 0 {
			vals["user_id"] = env.UID()
		}
		return vals
	}

	// action_open_project: Return an action to open the project.
	m.RegisterMethod("action_open_project", func(rs *orm.Recordset, args ...interface{}) (interface{}, error) {
		env := rs.Env()
		updateID := rs.IDs()[0]
		var projectID int64
		err := env.Tx().QueryRow(env.Ctx(),
			`SELECT project_id FROM project_update WHERE id = $1`, updateID).Scan(&projectID)
		if err != nil {
			return nil, fmt.Errorf("project_update: read update %d: %w", updateID, err)
		}
		return map[string]interface{}{
			"type":      "ir.actions.act_window",
			"res_model": "project.project",
			"res_id":    projectID,
			"view_mode": "form",
			"target":    "current",
		}, nil
	})
}
