# Authentication

## Personal access token

```elixir
client = ExFattureincloud.new(token: System.fetch_env!("FIC_ACCESS_TOKEN"))
```

Use a token with access to the selected company and the scopes required by your
operations. Pass the token explicitly or supply a zero-arity function that reads
it from your application. The SDK calls that function before each HTTP attempt.

## Authorization Code Flow

```elixir
alias ExFattureincloud.OAuth

client = ExFattureincloud.new()
state = OAuth.generate_state()
# Save state in the user's server-side session before redirecting.

url =
  OAuth.authorization_url(client,
    client_id: System.fetch_env!("FIC_CLIENT_ID"),
    redirect_uri: "https://example.com/oauth/fic/callback",
    scope: ["entity.clients:r", "issued_documents.invoices:a"],
    state: state
  )

# In the callback, read code and state from the query parameters.
:ok = OAuth.validate_state(saved_session_state, callback_state)
# Remove the validated state from the session so it can only be used once.

{:ok, token} =
  OAuth.exchange_code(client,
    client_id: System.fetch_env!("FIC_CLIENT_ID"),
    client_secret: System.fetch_env!("FIC_CLIENT_SECRET"),
    redirect_uri: "https://example.com/oauth/fic/callback",
    code: callback_code
  )

authenticated_client = ExFattureincloud.new(token: token.access_token)
```

Use the exact redirect URI registered with Fatture in Cloud. The `scope` option
accepts a space-separated string or a list of strings.
`ExFattureincloud.Scopes.all/0` lists the scopes in the pinned contract.
You can pass newer scope strings directly.
[Provider Authorization Code Flow guide](https://developers.fattureincloud.it/docs/authentication/code-flow/vanilla-code/)

## Refresh a token explicitly

```elixir
if OAuth.Token.expired?(saved_token) do
  {:ok, refreshed} =
    OAuth.refresh_token(client,
      client_id: System.fetch_env!("FIC_CLIENT_ID"),
      client_secret: System.fetch_env!("FIC_CLIENT_SECRET"),
      refresh_token: saved_token.refresh_token
    )

  token = %{refreshed | refresh_token: refreshed.refresh_token || saved_token.refresh_token}
  :ok = MyApp.FicCredentials.save_token(connection_id, token)
end
```

`OAuth.Token.expired?/2` uses a default margin of 60 seconds. Serialize refreshes
for each OAuth connection and save the access token, refresh token, and expiry
atomically. When the response omits a refresh token, keep the previous one.
You can supply a zero-arity token provider to read the current access token
from application storage.

## Supervised renewal

`ExFattureincloud.OAuth.TokenManager` coordinates renewal for one OAuth
connection. Save the initial token from `OAuth.exchange_code/2` or
`OAuth.device_token/2` before starting the manager.

```elixir
:ok = MyApp.FicCredentials.save_token(connection_id, token)
```

The two storage callbacks run application code. They follow these contracts.

- `load: fn -> ... end` returns `{:ok, %ExFattureincloud.OAuth.Token{}}` or
  `{:error, reason}`. Reconstruct the access token, refresh token, and
  `expires_at` Unix timestamp in seconds. Include `expires_in` where available
  so the manager can cap its refresh margin based on the token's lifetime.
- `save: fn token -> ... end` saves those credentials and the expiry in one
  transaction. Return `:ok` after commit or `{:error, reason}`. Convert a
  successful database result such as `{:ok, record}` to `:ok` in your callback.

Add the manager to your supervision tree.

```elixir
alias ExFattureincloud.OAuth.TokenManager

oauth_client = ExFattureincloud.new(
  req_options: [connect_options: [timeout: 5_000]]
)

children = [
  {TokenManager,
   id: {:fic_oauth, connection_id},
   name: MyApp.FicTokenManager,
   client: oauth_client,
   client_id: System.fetch_env!("FIC_CLIENT_ID"),
   client_secret: System.fetch_env!("FIC_CLIENT_SECRET"),
   load: fn -> MyApp.FicCredentials.load_token(connection_id) end,
   save: fn updated_token ->
     MyApp.FicCredentials.save_token(connection_id, updated_token)
   end,
   refresh_margin: 60,
   retry_interval: 30_000}
]

{:ok, _supervisor} = Supervisor.start_link(children, strategy: :one_for_one)

client = TokenManager.client(MyApp.FicTokenManager)
{:ok, companies} = ExFattureincloud.User.list_user_companies(client)
```

Use a unique name per connection, for example through `Registry`. Omit
`client_secret` for Device Code Flow. Use one manager even if the connection
covers several companies. Deployments with multiple nodes need a single owner
per connection or application-provided distributed coordination.

The manager loads credentials on startup and schedules a refresh before
expiration. The refresh margin is capped at half of `expires_in` when a
positive lifetime is available. With `automatic: false`, the manager refreshes
on demand. One asynchronous task performs the HTTP request and persistence for
all concurrent callers. A client returned by `TokenManager.client/1` retains the
configured HTTP settings and reads the current token from the manager.

```elixir
TokenManager.status(MyApp.FicTokenManager)
# %{status: :ready, expires_at: ..., pending_save?: false}

TokenManager.access_token(MyApp.FicTokenManager)
# {:ok, "..."} or {:error, %ExFattureincloud.Error{kind: :authentication}}
```

### Renewal failures and recovery

| Situation | Manager behavior |
| --- | --- |
| The refresh succeeds but persistence fails | The manager holds the rotated credentials in memory and retries saving after `retry_interval`. Calls return an authentication error while a save is pending. If the pending token expires, the manager saves it before attempting another refresh. |
| The provider returns HTTP 403 or 429 with `Retry-After` | Renewal waits at least as long as the provider requires. A valid cached access token remains usable. |
| A network, server, or protocol error leaves the result uncertain | The manager reports `:refresh_failed` and pauses renewal. Reconcile the credentials in your application. |
| The provider returns `invalid_grant` | The manager reports `:reauthorization_required`. Have the user authorize the connection again. |

After saving reconciled credentials, call `TokenManager.reload/1`.
Reloading is blocked while a refresh or a credential save is pending. Restore
storage availability and let the manager retry a pending save. If the process
crashes between remote renewal and successful persistence, it restarts from
the last stored credentials and may require reauthorization.

## Device Code Flow

Fatture in Cloud must enable this flow for your application.

```elixir
{:ok, device} = OAuth.device_code(client, client_id: "client-id", scope: ["settings:r"])

# Show user_code and verification_uri to the user. Keep device_code server-side.
poll_interval = device["interval"]

case OAuth.device_token(client, client_id: "client-id", device_code: device["device_code"]) do
  {:ok, token} ->
    {:ok, token}

  {:error, %{code: "authorization_pending"}} ->
    {:pending, poll_interval}

  {:error, %{code: "slow_down"}} ->
    {:pending, poll_interval + 5}

  {:error, error} ->
    {:error, error}
end
```

Each `OAuth.device_token/2` call makes one poll. Wait for the provider's
`interval` before the first poll and carry the returned interval forward for
later polls. Stop polling once the user authorizes, the code expires, or the
provider returns a terminal error. `OAuth.device_code/2` accepts both flat and
`data`-enveloped responses. Omit `client_secret` when refreshing a device token.
[Provider Device Code Flow guide](https://developers.fattureincloud.it/docs/authentication/device-code/), [RFC 8628, section 3.5](https://www.rfc-editor.org/rfc/rfc8628#section-3.5)
