<?php

namespace App\Console\Commands;

use App\Cawangan;
use App\Helper;
use Illuminate\Console\Command;

class CawanganDebugConnections extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cawangan:debug-connections';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Debugs cawangan connections';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $all_cawangan = Cawangan::withoutGlobalScopes()->where('db_name', 'like', 'arrahn_%')->get(['mysql', 'db_name'])->toArray();

        $all_cawangan_in_config = config('database.connections');
        $all_cawangan_in_config_keys = array_keys($all_cawangan_in_config);

        $all_cawangan_in_config = array_reduce($all_cawangan_in_config_keys, function ($accumulator, $current_key_value) use ($all_cawangan_in_config) {

            $accumulator[] = [
                'mysql' => $current_key_value,
                'database' => $all_cawangan_in_config[$current_key_value]['database'],
            ];

            return $accumulator;

        }, []);

        $all_cawangan_in_config = array_filter($all_cawangan_in_config, function ($connection) {

            $is_cawangan_databases = strpos($connection['database'], 'arrahn_') === 0;

            if ($is_cawangan_databases) {
                return true;
            }

        });

        function filterArraysByDatabaseNames($array1, $array2)
        {
            $idToNameMap = [];
            foreach ($array1 as $item) {
                $idToNameMap[$item['mysql']] = $item['db_name'];
            }

           $tested_connection = '';
           try {
            $filteredArray2 = array_filter($array2, function ($item) use ($idToNameMap) {
                $tested_connection = $idToNameMap[$item['mysql']];
                return $idToNameMap[$item['mysql']] !== $item['database'];
            });
           } catch (\Throwable $th) {
                dump(sprintf('Connection %s not found in table %s.arrahn_master_db but present in config. Make sure both of connection exist in both app/config and arrahn_master_db', $tested_connection, config('tennant_database.master_db')));
                return;
           }

            return $filteredArray2;
        }

        $filteredConnections = filterArraysByDatabaseNames($all_cawangan, $all_cawangan_in_config);

        if($filteredConnections === null OR sizeof($filteredConnections) > 1){
            return;
        }

        $isOK = true;

        // checks if there is connection errors
        if (sizeof(Helper::getInactiveCawanganDbConnection()) > 0) {
            dump('Inactive cawangan connection detected : ');
            dump('1. Check DB_HOST in .env status is alive and available');
            dump('2. Check database in .env exist in DB_HOST');
            dump('');
            dump(Helper::getInactiveCawanganDbConnection());
            $isOK = false;
        }

        // checks if config connection do not exist referring to arrahn_master_db
        if (count($all_cawangan) !== count($all_cawangan_in_config)) {
            $db_not_config = array_diff(array_column($all_cawangan, 'db_name'), array_column($all_cawangan_in_config, 'database'));

            dump(implode(', ', $db_not_config) . ' exist in arrahn_master_db but not configured in config/database.php');
            $isOK = false;
        }

       // checks if config connection databases are not tally fwith arrahn master db
        if (count($filteredConnections) !== 0) {
            dump('Database config names are not tally arrahn_master_db : ');
            dump($filteredConnections);
            $isOK = false;
        }

        if($isOK == true){
            dump('Cawangan database configuration is OK');
        }


    }
}
