package models

import "odoo-go/pkg/orm"

// TaxResult holds the result of computing a tax on an amount.
type TaxResult struct {
	TaxID     int64
	TaxName   string
	Amount    float64 // tax amount
	Base      float64 // base amount (before tax)
	AccountID int64   // account to post tax to
}

// ComputeTax calculates tax for a given base amount.
// Mirrors: odoo/addons/account/models/account_tax.py AccountTax._compute_amount()
func ComputeTax(env *orm.Environment, taxID int64, baseAmount float64) (*TaxResult, error) {
	var name string
	var amount float64
	var amountType string
	var priceInclude bool

	err := env.Tx().QueryRow(env.Ctx(),
		`SELECT name, amount, amount_type, COALESCE(price_include, false)
		 FROM account_tax WHERE id = $1`, taxID,
	).Scan(&name, &amount, &amountType, &priceInclude)
	if err != nil {
		return nil, err
	}

	var taxAmount float64
	switch amountType {
	case "percent":
		if priceInclude {
			taxAmount = baseAmount - (baseAmount / (1 + amount/100))
		} else {
			taxAmount = baseAmount * amount / 100
		}
	case "fixed":
		taxAmount = amount
	case "division":
		if priceInclude {
			taxAmount = baseAmount - (baseAmount / (1 + amount/100))
		} else {
			taxAmount = baseAmount * amount / 100
		}
	}

	// Find the tax account (from repartition lines)
	var accountID int64
	env.Tx().QueryRow(env.Ctx(),
		`SELECT COALESCE(account_id, 0) FROM account_tax_repartition_line
		 WHERE tax_id = $1 AND repartition_type = 'tax' AND document_type = 'invoice'
		 LIMIT 1`, taxID,
	).Scan(&accountID)

	// Fallback: use the USt account 1776 (SKR03)
	if accountID == 0 {
		env.Tx().QueryRow(env.Ctx(),
			`SELECT id FROM account_account WHERE code = '1776' LIMIT 1`,
		).Scan(&accountID)
	}

	return &TaxResult{
		TaxID:     taxID,
		TaxName:   name,
		Amount:    taxAmount,
		Base:      baseAmount,
		AccountID: accountID,
	}, nil
}
