import { color, utils } from '@heroku/heroku-cli-util';
import { Command, flags } from '@heroku-cli/command';
import { Args, ux } from '@oclif/core';
import tsheredoc from 'tsheredoc';
import backupsApi from '../../../lib/pg/backups.js';
import { nls } from '../../../nls.js';
const heredoc = tsheredoc.default;
export default class Capture extends Command {
    static args = {
        database: Args.string({ description: `${nls('pg:database:arg:description')} ${nls('pg:database:arg:description:default:suffix')}` }),
    };
    static description = 'capture a new backup';
    static flags = {
        app: flags.app({ required: true }),
        remote: flags.remote(),
        verbose: flags.boolean({ char: 'v' }),
        'wait-interval': flags.string(),
    };
    static topic = 'pg';
    async run() {
        const { args, flags } = await this.parse(Capture);
        const { app, verbose, 'wait-interval': waitInterval } = flags;
        const { database } = args;
        const interval = Math.max(3, Number.parseInt(waitInterval || '3', 10));
        const dbResolver = new utils.pg.DatabaseResolver(this.heroku);
        const { addon: db } = await dbResolver.getAttachment(app, database);
        const pgBackupsApi = backupsApi(app, this.heroku);
        try {
            const { body: dbInfo } = await this.heroku.get(`/client/v11/databases/${db.id}`, { hostname: utils.pg.host() });
            const dbProtected = /On/.test(dbInfo.info.find(attribute => attribute.name === 'Continuous Protection')?.values[0] || '');
            if (dbProtected) {
                ux.warn('Continuous protection is already enabled for this database. Logical backups of large databases are likely to fail.');
                ux.warn('See https://devcenter.heroku.com/articles/heroku-postgres-data-safety-and-continuous-protection#physical-backups-on-heroku-postgres.');
            }
        }
        catch (error) {
            const httpError = error;
            if (httpError.statusCode !== 404)
                throw httpError;
            ux.error(heredoc `
          ${color.datastore(db.name)} is not yet provisioned.
          Run ${color.code('heroku addons:wait')} to wait until the db is provisioned.
        `, { exit: 1 });
        }
        ux.action.start(`Starting backup of ${color.datastore(db.name)}`);
        const { body: backup } = await this.heroku.post(`/client/v11/databases/${db.id}/backups`, { hostname: utils.pg.host() });
        ux.action.stop();
        ux.stdout(heredoc `

      Use Ctrl-C at any time to stop monitoring progress; the backup will continue running.
      Use ${color.code('heroku pg:backups:info')} to check progress.
      Stop a running backup with ${color.code('heroku pg:backups:cancel')}.
    `);
        if (app !== db.app.name) {
            ux.stdout(heredoc `
        HINT: You are running this command with a non-billing application.
        Use ${color.code('heroku pg:backups -a ' + db.app.name)} to check the list of backups.
      `);
        }
        await pgBackupsApi.wait(`Backing up ${color.datastore(backup.from_name)} to ${color.cyan(pgBackupsApi.name(backup))}`, backup.uuid, interval, verbose, db.app.name || app);
    }
}
