package models

import "odoo-go/pkg/orm"

func Init() {
	initSaleOrder()
	initSaleOrderLine()
	initResPartnerSaleExtension()
	initSaleMargin()
}

// initResPartnerSaleExtension extends res.partner with sale-specific fields.
// Mirrors: odoo/addons/sale/models/res_partner.py
//
//	class ResPartner(models.Model):
//	    _inherit = 'res.partner'
//	    sale_order_count = fields.Integer(compute='_compute_sale_order_count')
//	    sale_order_ids = fields.One2many('sale.order', 'partner_id', string='Sales Orders')
func initResPartnerSaleExtension() {
	partner := orm.ExtendModel("res.partner")
	partner.AddFields(
		orm.One2many("sale_order_ids", "sale.order", "partner_id", orm.FieldOpts{
			String: "Sales Orders",
		}),
		orm.Integer("sale_order_count", orm.FieldOpts{
			String:  "Sale Order Count",
			Compute: "_compute_sale_order_count",
		}),
	)
	partner.RegisterCompute("sale_order_count", func(rs *orm.Recordset) (orm.Values, error) {
		env := rs.Env()
		partnerID := rs.IDs()[0]
		var count int
		err := env.Tx().QueryRow(env.Ctx(),
			`SELECT COUNT(*) FROM sale_order WHERE partner_id = $1`, partnerID,
		).Scan(&count)
		if err != nil {
			count = 0
		}
		return orm.Values{"sale_order_count": count}, nil
	})
}
