import { inject, injectable } from 'inversify';
import { Route53 } from 'aws-sdk';
import TYPES from '../container/IOC.types';
import BaseConfig from '../backends/configuration/abstractions/BaseConfig';

@injectable()
export default class Route53Service {
    @inject(TYPES.BackendConfig) private readonly config!: BaseConfig;

    public getRoute53Client(accessKeyId?: string, secretAccessKey?: string): Route53 {
        if (accessKeyId !== undefined && secretAccessKey !== undefined) {
            return new Route53({
                credentials: {
                    accessKeyId: accessKeyId,
                    secretAccessKey: secretAccessKey,
                },
            });
        }
        return new Route53();
    }

    public async createNewCNAME(
        route53Client: Route53,
        fromName: string,
        toName: string,
        ttl = 300,
    ): Promise<Route53.ChangeInfo> {
        const hostedZoneId = await this.config.getRoute53HostedZoneId();
        return new Promise((resolve, reject) => {
            route53Client.changeResourceRecordSets(
                {
                    ChangeBatch: {
                        Changes: [
                            {
                                Action: 'CREATE',
                                ResourceRecordSet: {
                                    Name: fromName,
                                    ResourceRecords: [
                                        {
                                            Value: toName,
                                        },
                                    ],
                                    TTL: ttl,
                                    Type: 'CNAME',
                                },
                            },
                        ],
                        Comment: 'Auto-generated by Scale8 API',
                    },
                    HostedZoneId: hostedZoneId, //fixed for *scale8.com
                },
                (err, data) => {
                    if (err) {
                        reject(`Failed to create CNAME for ${fromName}`);
                    } else {
                        resolve(data.ChangeInfo);
                    }
                },
            );
        });
    }
}
