package com.aip.gateway.api.aip;

import com.microsoft.aad.msal4j.ITokenCacheAccessAspect;
import com.microsoft.aad.msal4j.ITokenCacheAccessContext;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;

@Slf4j
public class TokenCacheAspect implements ITokenCacheAccessAspect {
    private String data;

    public TokenCacheAspect(String fileName) {
        this.data = readDataFromFile(fileName);
    }

    @Override
    public void beforeCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) {
        iTokenCacheAccessContext.tokenCache().deserialize(data);
    }

    @Override
    public void afterCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) {
        this.data = iTokenCacheAccessContext.tokenCache().serialize();
        // you could implement logic here to write changes to file
    }

    private static String readDataFromFile(String resource) {
        log.error("Resource: {}", resource);
        try {
            URL path = TokenCacheAspect.class.getResource(resource);
            log.error("Resource: {}", path);
            return new String(
                    Files.readAllBytes(Path.of(resource)));
//            return new String(
//                    Files.readAllBytes(
//                            Paths.get(path.toURI())));
        } catch (Exception ex){
            log.error("TokenCacheAspect: Error reading data from file: {}", ex.getMessage());
            throw new RuntimeException(ex);
        }
    }
}
