<?php

namespace Mtc\Plugins\Wisebee\Classes\Commands;

use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeConsultation;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeParticipant;
use Wisebee\Resources\Consultation;
use Wisebee\Wisebee;

class PullParticipantHashCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wisebee:participantHash';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Pulls and updates participant hashes of all participants';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $wisebee = new Wisebee(
            config('wisebee.host').config('wisebee.api_endpoint'),
            config('wisebee.api_key'),
        );

        $wisebeeConsultations = WisebeeConsultation::query()
            ->whereHas('participants', function (Builder $query): void {
                $query->whereNull('hash')
                    ->where('type', WisebeeParticipant::TYPE_CUSTOMER);
            })
            ->latest()
            ->get();

        foreach ($wisebeeConsultations as $wisebeeConsultation) {
            $remoteConsultation = $wisebee->get(Consultation::class, $wisebeeConsultation->wisebee_id);
            if (empty($remoteConsultation)) {
                continue;
            }

            foreach ($remoteConsultation->all_participants as $remoteParticipant) {
                WisebeeParticipant::query()
                    ->where('wisebee_id', $remoteParticipant->id)
                    ->update([
                        'hash' => $remoteParticipant->hash,
                    ]);
            }
        }

        return 0;
    }
}
