<?php

namespace App\Domains\Card\Jobs;

use App\Models\Card\Card;
use Illuminate\Support\Arr;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Dipper\Foundation\Bus\Dispatchable;
use App\Domains\Card\Services\CardService;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Domains\Card\Repositories\CardRepository;
use App\Domains\Virtual\Repositories\OrderCardPartitionRepository;

class MongoCardJob implements ShouldQueue
{
    use Queueable, Dispatchable;

    public $simArray;

    protected static $carrierOperators = [1, 0, 2];

    /**
     * Undocumented function
     *
     * @param array $simArray
     */
    public function __construct(array $simArray)
    {
        $this->simArray = $simArray;
    }

    /**
     *
     */
    public function handle()
    {
        foreach (array_chunk($this->simArray, 1000) as $simArray) {
            Log::notice('MongoCardJob #:' . implode(',', $simArray));
            $this->cardsJob($simArray);
        }
    }

    public function cardsJob($simArray)
    {
        $values = CardService::getMongoCardsInfo($simArray);

        if (empty($values)) {
            Log::notice('MongoCardJob not result!');
            return ;
        }

        $builder = Card::query()->toBase();

        $sql = $builder->getGrammar()->compileInsert($builder, $values);

        $sql .= ' on conflict (sim) do update set
            imsi=excluded.imsi,
            iccid=excluded.iccid,
            carrier_operator=excluded.carrier_operator,
            activated_at=excluded.activated_at,
            virtual_activated_at=COALESCE(cards.virtual_activated_at, excluded.activated_at),
            created_at=excluded.created_at,
            updated_at=excluded.updated_at
        ';

        $builder->connection->insert($sql, Arr::flatten($values, 1));

        app(CardRepository::class)->forgetCached();

        $simArray = implode(',', array_keys($values));

        DB::statement("select fix_timelines('{{$simArray}}'::INT8[]);");

        app(OrderCardPartitionRepository::class)->forgetCached();
    }
}
