from __future__ import annotations

from datetime import UTC, datetime, timedelta

from pydantic import BaseModel, Field


class EbayOAuthConfig(BaseModel):
    client_id: str
    client_secret: str
    redirect_uri: str | None = None
    auth_base_url: str = "https://auth.ebay.com/oauth2/authorize"
    token_url: str = "https://api.ebay.com/identity/v1/oauth2/token"
    default_scopes: list[str] = Field(default_factory=list)


class OAuthToken(BaseModel):
    access_token: str
    token_type: str = "Bearer"
    expires_in: int = 7200
    scope: str | None = None
    refresh_token: str | None = None
    refresh_token_expires_in: int | None = None
    obtained_at: datetime = Field(default_factory=lambda: datetime.now(UTC))

    @property
    def expires_at(self) -> datetime:
        return self.obtained_at + timedelta(seconds=self.expires_in)

    def is_expired(self, *, skew_seconds: int = 30) -> bool:
        return datetime.now(UTC) >= self.expires_at - timedelta(seconds=skew_seconds)

    def scopes(self) -> set[str]:
        if not self.scope:
            return set()
        return {value for value in self.scope.split() if value}
