from __future__ import annotations

import base64
from typing import Any

import httpx


def bearer_auth_header(api_key: str) -> dict[str, str]:
    if not api_key:
        raise ValueError("api_key is required for bearer authentication")
    return {"Authorization": f"Bearer {api_key}"}


def basic_auth_header(email: str, api_key: str) -> dict[str, str]:
    if not email:
        raise ValueError("email is required for basic authentication")
    if not api_key:
        raise ValueError("api_key is required for basic authentication")

    token = base64.b64encode(f"{email}:{api_key}".encode("utf-8")).decode("ascii")
    return {"Authorization": f"Basic {token}"}


class EasybillAuth(httpx.Auth):
    def __init__(self, api_key: str, *, email: str | None = None, use_basic_auth: bool = False) -> None:
        self.api_key = api_key
        self.email = email
        self.use_basic_auth = use_basic_auth

    def build_headers(self) -> dict[str, str]:
        if self.use_basic_auth:
            if not self.email:
                raise ValueError("email must be provided when use_basic_auth is enabled")
            return basic_auth_header(self.email, self.api_key)
        return bearer_auth_header(self.api_key)

    def auth_flow(self, request: httpx.Request) -> Any:
        request.headers.update(self.build_headers())
        yield request
