<?php

namespace Ignite\Core\Console;

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

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

    /**
     * @var string
     */
    protected $description = 'Decrypt a column on the given table, 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');

        $value = DB::table($table)->where($keyName, $keyValue)->value($column);

        try {
            $this->info(decrypt($value) ?? 'null');

            return 0;
        } catch (\Exception $e) {
            $this->error("Unable to decrypt {$column} on {$table}: $value");

            return 1;
        }
    }
}
