"""Module section forms: stockroom default price rule + per-listing price edit."""

from django import forms

from ...forms import AddStockroomForm
from ...models import FIXED_PRICE, PCT_MODES, PRICE_MODE_CHOICES


def _price_pct_field():
    return forms.DecimalField(
        min_value=0, max_digits=5, decimal_places=2, required=False
    )


class ModuleStockroomForm(AddStockroomForm):
    """Module stockroom adds a default price rule inherited by first-seen modules."""

    price_mode = forms.ChoiceField(choices=PRICE_MODE_CHOICES)
    price_pct = _price_pct_field()

    def clean(self):
        cleaned = super().clean()
        if cleaned.get("price_mode") in PCT_MODES and not cleaned.get("price_pct"):
            self.add_error("price_pct", "Enter a percentage for %-based pricing.")
        return cleaned


class EditStockroomForm(forms.Form):
    """Edit a module stockroom's default price rule."""

    price_mode = forms.ChoiceField(choices=PRICE_MODE_CHOICES)
    price_pct = _price_pct_field()

    def clean(self):
        cleaned = super().clean()
        if cleaned.get("price_mode") in PCT_MODES and not cleaned.get("price_pct"):
            self.add_error("price_pct", "Enter a percentage for %-based pricing.")
        return cleaned


class EditModuleForm(forms.Form):
    """Per-listing price override (fixed ISK or % Jita) — no stock fields."""

    price_mode = forms.ChoiceField(choices=PRICE_MODE_CHOICES)
    price = forms.IntegerField(min_value=0, required=False)  # ISK, fixed mode
    price_pct = _price_pct_field()

    def clean(self):
        cleaned = super().clean()
        if cleaned.get("price_mode") == FIXED_PRICE and cleaned.get("price") is None:
            self.add_error("price", "Enter a price (0 = Ask) for fixed price.")
        if cleaned.get("price_mode") in PCT_MODES and not cleaned.get("price_pct"):
            self.add_error("price_pct", "Enter a percentage for %-based pricing.")
        return cleaned
