"""
Validaciones comunes de fila para import CSV de BOMs.
"""
from decimal import Decimal
from typing import Dict, Any, Optional, Set

from ..common.common_validators import (
    check_max_length,
    check_decimal_required_min,
    check_optional_number,
    check_in_set,
)


def validate_row_required_parent(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    return check_max_length(row, "NUMPARTE_PADRE", 70, line_num, required=True)


def validate_row_required_component(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    return check_max_length(row, "NUMPARTE_COMPONENTE", 70, line_num, required=True)


def validate_row_quantity(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    return check_decimal_required_min(row, "CANTIDAD", line_num, Decimal("0"))


def validate_row_lengths(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    return check_max_length(row, "UNIMED", 10, line_num)


def validate_row_optional_numbers(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    err = check_optional_number(row, "VERSION_BOM", line_num)
    if err:
        return err
    return check_optional_number(row, "VERSION_BILL", line_num)


def validate_row_fks(
    row: Dict[str, Any],
    line_num: int,
    valid_part_numbers: Optional[Set[str]],
) -> Optional[Dict[str, Any]]:
    if not valid_part_numbers or len(valid_part_numbers) == 0:
        return None
    err = check_in_set(
        row, "NUMPARTE_PADRE", line_num,
        valid_part_numbers, "Parte padre no existe en catálogo",
    )
    if err:
        return err
    return check_in_set(
        row, "NUMPARTE_COMPONENTE", line_num,
        valid_part_numbers, "Parte componente no existe en catálogo",
    )
