"""Bounded OAuth form decoding, including duplicate parameter rejection."""

from urllib.parse import parse_qsl

from fastapi import Request

from src.core.exceptions import ValidationError


async def read_oauth_form(request: Request) -> dict[str, str]:
    if (
        request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
        != "application/x-www-form-urlencoded"
    ):
        raise ValidationError("Expected an OAuth form")
    body = bytearray()
    async for chunk in request.stream():
        if len(body) + len(chunk) > 16_384:
            raise ValidationError("OAuth form too large")
        body.extend(chunk)
    try:
        pairs = parse_qsl(
            body.decode("utf-8"), keep_blank_values=True, max_num_fields=20, errors="strict"
        )
    except ValueError:
        raise ValidationError("Invalid OAuth form") from None
    if len({key for key, _ in pairs}) != len(pairs):
        raise ValidationError("Duplicate OAuth parameter")
    return dict(pairs)
