import { PlatformClient, PlatformConfig } from "@gofynd/fdk-client-javascript";
import Redis from "ioredis"
const redis = new Redis({
    host: 'redis-12291.c305.ap-south-1-1.ec2.cloud.redislabs.com',
    port: 12291,
    password: 'KQCVapXXF2ioM4zF5krQFImzAYkKWY5l',
    username: "default"
});

export const initClient = async (companyId) => {
    let creds = await redis.get(`${companyId}:creds`);
    if (!creds) throw {
        message: "company creds not found"
    }
    creds = JSON.parse(creds)

    const config = {
        companyId: parseInt(companyId),
        apiKey: creds.clientId,
        apiSecret: creds.clientSecret,
        useAutoRenewTimer: true,
        domain: "https://api.fyndx5.de",
        logLevel: "DEBUG"
    }
    const platformConfig = new PlatformConfig(config)
    let token = await redis.get(`${companyId}:client_token`)
    if (!token) {
        token = await platformConfig.oauthClient.getAccesstokenObj({
            grant_type: 'client_credentials'
        });
        await redis.set(`${companyId}:client_token`, JSON.stringify(token), "EX", 60 * 30);
    } else {
        token = JSON.parse(token)
    }
    platformConfig.oauthClient.setToken(token);
    return new PlatformClient(platformConfig);
}