# Copyright (C) 2020: Criptomart (https://criptomart.net)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from odoo.tests import tagged
from odoo.tests.common import TransactionCase


@tagged("post_install", "-at_install")
class TestResConfigSettings(TransactionCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()

        cls.pricelist = cls.env["product.pricelist"].create(
            {
                "name": "Test Config Pricelist",
                "currency_id": cls.env.company.currency_id.id,
            }
        )

    def test_config_parameter_set_and_get(self):
        """Test setting and getting pricelist configuration"""
        config = self.env["res.config.settings"].create(
            {
                "product_pricelist_automatic": self.pricelist.id,
            }
        )

        config.execute()

        # Verify parameter was saved
        saved_id = (
            self.env["ir.config_parameter"]
            .sudo()
            .get_param("product_sale_price_from_pricelist.product_pricelist_automatic")
        )

        self.assertEqual(int(saved_id), self.pricelist.id)

    def test_config_load_from_parameter(self):
        """Test loading pricelist from config parameter"""
        # Set parameter directly
        self.env["ir.config_parameter"].sudo().set_param(
            "product_sale_price_from_pricelist.product_pricelist_automatic",
            str(self.pricelist.id),
        )

        # Create config and check if value is loaded
        config = self.env["res.config.settings"].create({})

        self.assertEqual(config.product_pricelist_automatic.id, self.pricelist.id)

    def test_config_update_pricelist(self):
        """Test updating pricelist configuration"""
        # Set initial pricelist
        config = self.env["res.config.settings"].create(
            {
                "product_pricelist_automatic": self.pricelist.id,
            }
        )
        config.execute()

        # Create new pricelist and update
        new_pricelist = self.env["product.pricelist"].create(
            {
                "name": "New Config Pricelist",
                "currency_id": self.env.company.currency_id.id,
            }
        )

        config2 = self.env["res.config.settings"].create(
            {
                "product_pricelist_automatic": new_pricelist.id,
            }
        )
        config2.execute()

        # Verify new value
        saved_id = (
            self.env["ir.config_parameter"]
            .sudo()
            .get_param("product_sale_price_from_pricelist.product_pricelist_automatic")
        )

        self.assertEqual(int(saved_id), new_pricelist.id)

    def test_config_without_pricelist(self):
        """Test configuration can be saved without pricelist"""
        config = self.env["res.config.settings"].create({})

        # Should not raise error
        config.execute()
