import assert from 'node:assert';
import AuditSource from '../auditsource.js';
import BoxError from '../boxerror.js';
import { HttpError } from '@cloudron/connect-lastmile';
import { HttpSuccess } from '@cloudron/connect-lastmile';
import network from '../network.js';
import provision from '../provision.js';
import safe from 'safetydance';
import superagent from '@cloudron/superagent';
import system from '../system.js';
import users from '../users.js';


async function verifyUnprovisioned(req, res, next) {
    const activated = await users.isActivated();
    if (activated) return next(new HttpError(405, 'route unavailable post activation'));

    next();
}

async function providerTokenAuth(req, res, next) {
    assert.strictEqual(typeof req.body, 'object');

    if (system.getProvider() === 'ami') {
        if (typeof req.body.providerToken !== 'string' || !req.body.providerToken) return next(new HttpError(400, 'providerToken must be a non empty string'));

        // IMDSv2 https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-options.html
        // https://aws.amazon.com/blogs/security/defense-in-depth-open-firewalls-reverse-proxies-ssrf-vulnerabilities-ec2-instance-metadata-service/
        const imdsIp = req.body.ipv4Config?.provider === 'noop' ? '[fd00:ec2::254]' : '169.254.169.254'; // use ipv4config carefully, it's not validated yet at this point
        const [tokenError, tokenResponse] = await safe(superagent.put(`http://${imdsIp}/latest/api/token`).set('x-aws-ec2-metadata-token-ttl-seconds', 600).timeout(30 * 1000).ok(() => true));
        if (tokenError) return next(new HttpError(422, `Network error getting EC2 metadata session token: ${tokenError.message}`));
        if (tokenResponse.status !== 200) return next(new HttpError(422, `Unable to get EC2 meta data session token. status: ${tokenResponse.status}`));
        const imdsToken = tokenResponse.text;

        const [error, response] = await safe(superagent.get(`http://${imdsIp}/latest/meta-data/instance-id`).set('x-aws-ec2-metadata-token', imdsToken).timeout(30 * 1000).ok(() => true));
        if (error) return next(new HttpError(422, `Network error getting EC2 metadata: ${error.message}`));
        if (response.status !== 200) return next(new HttpError(422, `Unable to get EC2 meta data. status: ${response.status}`));
        if (response.text !== req.body.providerToken) return next(new HttpError(422, 'Instance ID does not match'));

        next();
    } else {
        next();
    }
}

async function setup(req, res, next) {
    assert.strictEqual(typeof req.body, 'object');

    if (!req.body.domainConfig || typeof req.body.domainConfig !== 'object') return next(new HttpError(400, 'domainConfig is required'));

    const domainConfig = req.body.domainConfig;

    if (typeof domainConfig.provider !== 'string' || !domainConfig.provider) return next(new HttpError(400, 'provider is required'));
    if (typeof domainConfig.domain !== 'string' || !domainConfig.domain) return next(new HttpError(400, 'domain is required'));

    if ('zoneName' in domainConfig && typeof domainConfig.zoneName !== 'string') return next(new HttpError(400, 'zoneName must be a string'));
    if (!domainConfig.config || typeof domainConfig.config !== 'object') return next(new HttpError(400, 'config must be an object'));

    if ('tlsConfig' in domainConfig && typeof domainConfig.tlsConfig !== 'object') return next(new HttpError(400, 'tlsConfig must be an object'));
    if (domainConfig.tlsConfig && (!domainConfig.tlsConfig.provider || typeof domainConfig.tlsConfig.provider !== 'string')) return next(new HttpError(400, 'tlsConfig.provider must be a string'));

    if ('ipv4Config' in req.body && typeof req.body.ipv4Config !== 'object') return next(new HttpError(400, 'ipv4Config must be an object'));
    if ('ipv6Config' in req.body && typeof req.body.ipv6Config !== 'object') return next(new HttpError(400, 'ipv6Config must be an object'));

    // it can take sometime to setup DNS, register cloudron
    req.clearTimeout();

    const [error] = await safe(provision.setup(domainConfig, req.body.ipv4Config || { provider: 'generic' }, req.body.ipv6Config || { provider: 'generic' }, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(200, {}));
}

async function activate(req, res, next) {
    assert.strictEqual(typeof req.body, 'object');

    if (typeof req.body.username !== 'string') return next(new HttpError(400, 'username must be string'));
    if (typeof req.body.password !== 'string') return next(new HttpError(400, 'password must be string'));
    if (typeof req.body.email !== 'string') return next(new HttpError(400, 'email must be string'));
    if ('displayName' in req.body && typeof req.body.displayName !== 'string') return next(new HttpError(400, 'displayName must be string'));

    const { username, password, email } = req.body;
    const displayName = req.body.displayName || '';

    const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;

    const [error, result] = await safe(provision.activate(username, password, email, displayName, ip, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(201, result));
}

async function restore(req, res, next) {
    assert.strictEqual(typeof req.body, 'object');

    if (!req.body.backupConfig || typeof req.body.backupConfig !== 'object') return next(new HttpError(400, 'backupConfig is required'));

    const backupConfig = req.body.backupConfig;
    if (typeof backupConfig.provider !== 'string') return next(new HttpError(400, 'backupConfig.provider is required'));
    if (typeof backupConfig.format !== 'string') return next(new HttpError(400, 'backupConfig.format must be a string'));
    if (typeof backupConfig.config !== 'object') return next(new HttpError(400, 'backupConfig.config must be an object'));

    if ('encryptionPassword' in backupConfig && typeof backupConfig.encryptionPassword !== 'string') return next(new HttpError(400, 'backupConfig.encryptionPassword must be a string'));
    if ('encryptedFilenames' in req.body && typeof req.body.encryptedFilenames !== 'boolean') return next(new HttpError(400, 'backupConfig.encryptedFilenames must be a boolean'));

    if (typeof req.body.remotePath !== 'string') return next(new HttpError(400, 'remotePath must be a string'));
    if (typeof req.body.version !== 'string') return next(new HttpError(400, 'version must be a string'));

    if ('ipv4Config' in req.body && typeof req.body.ipv4Config !== 'object') return next(new HttpError(400, 'ipv4Config must be an object'));
    if ('ipv6Config' in req.body && typeof req.body.ipv6Config !== 'object') return next(new HttpError(400, 'ipv6Config must be an object'));

    if ('skipDnsSetup' in req.body && typeof req.body.skipDnsSetup !== 'boolean') return next(new HttpError(400, 'skipDnsSetup must be a boolean'));
    if ('siteId' in req.body && typeof req.body.siteId !== 'string') return next(new HttpError(400, 'siteId must be a string'));

    const options = {
        skipDnsSetup: req.body.skipDnsSetup || false,
        siteId: req.body.siteId || null
    };

    const [error] = await safe(provision.restore(backupConfig, req.body.remotePath, req.body.version, req.body.ipv4Config || { provider: 'generic' }, req.body.ipv6Config || { provider: 'generic' }, options, AuditSource.fromRequest(req)));
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(200, {}));
}

async function getStatus(req, res, next) {
    const [error, status] = await safe(provision.getStatus());
    if (error) return next(BoxError.toHttpError(error));

    next(new HttpSuccess(200, status));
}

async function getBlockDevices(req, res, next) {
    const [error, devices] = await safe(system.getBlockDevices());
    if (error) return next(new HttpError(500, error));

    next(new HttpSuccess(200, { devices }));
}

async function detectIP(req, res, next) {
    const result = await network.detectIP();
    next(new HttpSuccess(200, { ipv4: result.ipv4, ipv6: result.ipv6 }));
}

export default {
    providerTokenAuth,
    verifyUnprovisioned,
    setup,
    activate,
    restore,
    getStatus,
    getBlockDevices,
    detectIP
};
