# Copyright 2026 Criptomart
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

from odoo.tests.common import TransactionCase


class TestProjectTaskAnalyticAccountSync(TransactionCase):
    def setUp(self):
        super().setUp()
        self.AnalyticAccount = self.env["account.analytic.account"]
        self.Project = self.env["project.project"]
        self.Task = self.env["project.task"]

        self.plan = self.env["account.analytic.plan"].create(
            {"name": "Test Plan", "company_id": self.env.company.id}
        )

        self.analytic_1 = self.AnalyticAccount.create(
            {"name": "Analytic Account 1", "plan_id": self.plan.id}
        )
        self.analytic_2 = self.AnalyticAccount.create(
            {"name": "Analytic Account 2", "plan_id": self.plan.id}
        )

        self.project_a = self.Project.create(
            {
                "name": "Project A",
                "analytic_account_id": self.analytic_1.id,
            }
        )
        self.project_b = self.Project.create(
            {
                "name": "Project B",
                "analytic_account_id": self.analytic_2.id,
            }
        )

    def test_task_sync_on_create(self):
        """RF-03: a new task must adopt the project's analytic account."""
        task = self.Task.create(
            {
                "name": "Test Task",
                "project_id": self.project_a.id,
            }
        )
        self.assertEqual(task.analytic_account_id, self.analytic_1)

    def test_task_sync_on_project_change(self):
        """RF-04: moving a task to another project updates its analytic account."""
        task = self.Task.create(
            {
                "name": "Test Task",
                "project_id": self.project_a.id,
            }
        )
        self.assertEqual(task.analytic_account_id, self.analytic_1)
        task.write({"project_id": self.project_b.id})
        self.assertEqual(task.analytic_account_id, self.analytic_2)

    def test_task_sync_on_project_analytic_change(self):
        """RF-02: changing the project's analytic account propagates to tasks."""
        task = self.Task.create(
            {
                "name": "Test Task",
                "project_id": self.project_a.id,
            }
        )
        self.assertEqual(task.analytic_account_id, self.analytic_1)
        self.project_a.write({"analytic_account_id": self.analytic_2.id})
        self.assertEqual(task.analytic_account_id, self.analytic_2)

    def test_task_sync_overrides_manual_change(self):
        """RF-01: a manual change on the task must be reverted immediately."""
        task = self.Task.create(
            {
                "name": "Test Task",
                "project_id": self.project_a.id,
            }
        )
        self.assertEqual(task.analytic_account_id, self.analytic_1)
        task.write({"analytic_account_id": self.analytic_2.id})
        self.assertEqual(task.analytic_account_id, self.analytic_1)
