package com.ai.trackwalker.uavaccess.flighthub;

import com.ai.trackwalker.uavaccess.config.UavAccessProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

@Component
public class SecretTokenProvider {
    private final UavAccessProperties properties;

    public SecretTokenProvider(UavAccessProperties properties) {
        this.properties = properties;
    }

    public String token() {
        String configured = properties.getFlighthub().getUserToken();
        if (configured != null && !configured.isBlank()) {
            return configured.trim();
        }
        String file = properties.getFlighthub().getUserTokenFile();
        if (file == null || file.isBlank()) {
            throw new FlightHubException(
                    503, "", "CONFIGURATION_REQUIRED", "",
                    "FlightHub x-user-token is not configured", null
            );
        }
        try {
            String value = Files.readString(Path.of(file), StandardCharsets.UTF_8).trim();
            if (value.isBlank()) throw new IOException("secret file is empty");
            return value;
        } catch (IOException exception) {
            throw new FlightHubException(
                    503, "", "CONFIGURATION_REQUIRED", "",
                    "Unable to read FlightHub token file", exception
            );
        }
    }
}
