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

"""
Test suite for Phase 1 refactoring helper methods.

Tests for extracted helper methods that reduce cyclomatic complexity:
- _resolve_pricelist(): Consolidate pricelist resolution logic
- _validate_confirm_request(): Validate confirm order request
- _validate_draft_request(): Validate draft order request
"""

from datetime import datetime
from datetime import timedelta

from odoo.tests.common import TransactionCase


class TestResolvePricelist(TransactionCase):
    """Test _resolve_pricelist() helper method."""

    def setUp(self):
        super().setUp()
        self.pricelist_aplicoop = self.env["product.pricelist"].create(
            {
                "name": "Aplicoop Pricelist",
                "currency_id": self.env.company.currency_id.id,
            }
        )

        self.pricelist_website = self.env["product.pricelist"].create(
            {
                "name": "Website Pricelist",
                "currency_id": self.env.company.currency_id.id,
            }
        )

        self.website = self.env["website"].get_current_website()
        self.website.pricelist_id = self.pricelist_website.id

    def test_resolve_pricelist_aplicoop_configured(self):
        """Test pricelist resolution when Aplicoop pricelist is configured."""
        # Set Aplicoop pricelist in config
        self.env["ir.config_parameter"].sudo().set_param(
            "website_sale_aplicoop.pricelist_id", str(self.pricelist_aplicoop.id)
        )

        # When calling _resolve_pricelist, should return Aplicoop pricelist
        # Placeholder: will be implemented with actual controller call

    def test_resolve_pricelist_fallback_to_website(self):
        """Test fallback to website pricelist when Aplicoop not configured."""
        # Don't set Aplicoop pricelist in config (leave empty)
        self.env["ir.config_parameter"].sudo().set_param(
            "website_sale_aplicoop.pricelist_id", ""
        )

        # When calling _resolve_pricelist, should return website pricelist
        # Placeholder: will be implemented with actual controller call

    def test_resolve_pricelist_fallback_to_first_active(self):
        """Test final fallback to first active pricelist."""
        # Remove both configured pricelists
        self.env["ir.config_parameter"].sudo().set_param(
            "website_sale_aplicoop.pricelist_id", ""
        )
        self.website.pricelist_id = False

        # When calling _resolve_pricelist, should return first active pricelist
        # Placeholder: will be implemented with actual controller call


class TestValidateConfirmRequest(TransactionCase):
    """Test _validate_confirm_request() helper method."""

    def setUp(self):
        super().setUp()
        self.group = self.env["res.partner"].create(
            {
                "name": "Test Group",
                "is_company": True,
            }
        )

        self.member = self.env["res.partner"].create(
            {
                "name": "Group Member",
                "email": "member@test.com",
            }
        )
        self.group.member_ids = [(4, self.member.id)]

        self.user = self.env["res.users"].create(
            {
                "name": "Test User",
                "login": "testuser@test.com",
                "email": "testuser@test.com",
                "partner_id": self.member.id,
            }
        )

        self.product = self.env["product.product"].create(
            {
                "name": "Test Product",
                "type": "product",
                "list_price": 100.0,
            }
        )

        self.group_order = self.env["group.order"].create(
            {
                "name": "Test Order",
                "group_ids": [(4, self.group.id)],
                "start_date": datetime.now().date(),
                "end_date": datetime.now().date() + timedelta(days=7),
                "pickup_day": "3",
                "cutoff_day": "0",
                "state": "open",
            }
        )

    def test_validate_confirm_valid_request(self):
        """Test validation passes for valid confirm request."""
        _ = {
            "order_id": str(self.group_order.id),
            "items": [
                {
                    "product_id": str(self.product.id),
                    "quantity": 1.0,
                    "product_price": 100.0,
                }
            ],
            "is_delivery": False,
        }

        # Validation should pass without raising exception
        # Placeholder: will be implemented with actual controller call

    def test_validate_confirm_missing_order_id(self):
        """Test validation fails when order_id missing."""
        _ = {
            "items": [{"product_id": "1", "quantity": 1.0}],
        }

        # Validation should raise ValueError: "order_id is required"
        # Placeholder: will be implemented with actual controller call

    def test_validate_confirm_invalid_order_id(self):
        """Test validation fails for invalid order_id format."""
        _ = {
            "order_id": "invalid",
            "items": [{"product_id": "1", "quantity": 1.0}],
        }

        # Validation should raise ValueError with "Invalid order_id format"
        # Placeholder: will be implemented with actual controller call

    def test_validate_confirm_nonexistent_order(self):
        """Test validation fails when order doesn't exist."""
        _ = {
            "order_id": "99999",
            "items": [{"product_id": "1", "quantity": 1.0}],
        }

        # Validation should raise ValueError with "not found"
        # Placeholder: will be implemented with actual controller call

    def test_validate_confirm_closed_order(self):
        """Test validation fails when order is closed."""
        self.group_order.state = "confirmed"

        _ = {
            "order_id": str(self.group_order.id),
            "items": [{"product_id": "1", "quantity": 1.0}],
        }

        # Validation should raise ValueError with "not available"
        # Placeholder: will be implemented with actual controller call

    def test_validate_confirm_no_items(self):
        """Test validation fails when no items provided."""
        _ = {
            "order_id": str(self.group_order.id),
            "items": [],
        }

        # Validation should raise ValueError with "No items in cart"
        # Placeholder: will be implemented with actual controller call

    def test_validate_confirm_user_no_partner(self):
        """Test validation fails when user has no partner_id."""
        _ = self.env["res.users"].create(
            {
                "name": "User No Partner",
                "login": "nopartner@test.com",
                "email": "nopartner@test.com",
            }
        )

        _ = {
            "order_id": str(self.group_order.id),
            "items": [{"product_id": "1", "quantity": 1.0}],
        }

        # Validation should raise ValueError with "no associated partner"
        # Placeholder: will be implemented with actual controller call


class TestValidateDraftRequest(TransactionCase):
    """Test _validate_draft_request() helper method."""

    def setUp(self):
        super().setUp()
        self.group = self.env["res.partner"].create(
            {
                "name": "Test Group",
                "is_company": True,
            }
        )

        self.member = self.env["res.partner"].create(
            {
                "name": "Group Member",
                "email": "member@test.com",
            }
        )
        self.group.member_ids = [(4, self.member.id)]

        self.user = self.env["res.users"].create(
            {
                "name": "Test User",
                "login": "testuser@test.com",
                "email": "testuser@test.com",
                "partner_id": self.member.id,
            }
        )

        self.product = self.env["product.product"].create(
            {
                "name": "Test Product",
                "type": "product",
                "list_price": 100.0,
            }
        )

        self.group_order = self.env["group.order"].create(
            {
                "name": "Test Order",
                "group_ids": [(4, self.group.id)],
                "start_date": datetime.now().date(),
                "end_date": datetime.now().date() + timedelta(days=7),
                "pickup_day": "3",
                "cutoff_day": "0",
                "state": "open",
            }
        )

    def test_validate_draft_valid_request(self):
        """Test validation passes for valid draft request."""
        _ = {
            "order_id": str(self.group_order.id),
            "items": [
                {
                    "product_id": str(self.product.id),
                    "quantity": 1.0,
                    "product_price": 100.0,
                }
            ],
        }

        # Validation should pass without raising exception
        # Placeholder: will be implemented with actual controller call

    def test_validate_draft_missing_order_id(self):
        """Test validation fails when order_id missing."""
        _ = {
            "items": [{"product_id": "1", "quantity": 1.0}],
        }

        # Validation should raise ValueError: "order_id is required"
        # Placeholder: will be implemented with actual controller call

    def test_validate_draft_invalid_order_id(self):
        """Test validation fails for invalid order_id."""
        _ = {
            "order_id": "invalid",
            "items": [{"product_id": "1", "quantity": 1.0}],
        }

        # Validation should raise ValueError with "Invalid order_id format"
        # Placeholder: will be implemented with actual controller call

    def test_validate_draft_nonexistent_order(self):
        """Test validation fails when order doesn't exist."""
        _ = {
            "order_id": "99999",
            "items": [{"product_id": "1", "quantity": 1.0}],
        }

        # Validation should raise ValueError with "not found"
        # Placeholder: will be implemented with actual controller call

    def test_validate_draft_no_items(self):
        """Test validation fails when no items."""
        _ = {
            "order_id": str(self.group_order.id),
            "items": [],
        }

        # Validation should raise ValueError with "No items in cart"
        # Placeholder: will be implemented with actual controller call

    def test_validate_draft_user_no_partner(self):
        """Test validation fails when user has no partner."""
        _ = self.env["res.users"].create(
            {
                "name": "User No Partner",
                "login": "nopartner@test.com",
                "email": "nopartner@test.com",
            }
        )

        _ = {
            "order_id": str(self.group_order.id),
            "items": [{"product_id": "1", "quantity": 1.0}],
        }

        # Validation should raise ValueError with "no associated partner"
        # Placeholder: will be implemented with actual controller call

    def test_validate_draft_with_merge_action(self):
        """Test validation passes when merge_action is specified."""
        _ = {
            "order_id": str(self.group_order.id),
            "items": [{"product_id": "1", "quantity": 1.0}],
            "merge_action": "merge",
            "existing_draft_id": "123",
        }

        # Validation should pass and return merge_action and existing_draft_id
        # Placeholder: will be implemented with actual controller call

    def test_validate_draft_with_replace_action(self):
        """Test validation passes when replace_action is specified."""
        _ = {
            "order_id": str(self.group_order.id),
            "items": [{"product_id": "1", "quantity": 1.0}],
            "merge_action": "replace",
            "existing_draft_id": "123",
        }

        # Validation should pass and return merge_action and existing_draft_id
        # Placeholder: will be implemented with actual controller call
