<?php

namespace Ignite\Core\Console\Data;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class Decrypt extends Command
{
    /**
     * @var string
     */
    protected $signature = 'ignite:data:decrypt {table} {column} {key-name?} {key-value?}';

    /**
     * @var string
     */
    protected $description = 'Decrypt a column on the given table to output, optionally using the given key.';

    /**
     * Handle the command.
     *
     * @return int
     */
    public function handle()
    {
        $table = $this->argument('table');
        $column = $this->argument('column');
        $keyName = $this->argument('key-name');
        $keyValue = $this->argument('key-value');

        if ($keyName) {
            $values = [ DB::table($table)->where($keyName, $keyValue)->value($column) ];
        } else {
            $values = DB::table($table)->pluck($column);
        }

        foreach ($values as $value) {
            try {
                $this->info(decrypt($value) ?? 'null');
            } catch (\Exception $e) {
                $this->error("Unable to decrypt {$column} on {$table}: $value");
            }
        }
    }
}
