<?php

namespace App\Services;

use App\Models\ClientProviderBlock;
use Exception;

class ClientProviderBlockService
{
    public function getByClientId(int $clientId)
    {
        return ClientProviderBlock::where('client_provider_blocks.client_id', $clientId)
            ->leftJoin('providers', 'providers.id', '=', 'client_provider_blocks.provider_id')
            ->leftJoin('users as provider_user', 'provider_user.id', '=', 'providers.user_id')
            ->leftJoin('addresses as provider_address', function ($join) {
                $join->on('provider_address.source_id', '=', 'providers.id')
                    ->where('provider_address.source', 'provider')
                    ->whereNull('provider_address.deleted_at');
            })
            ->select(
                'client_provider_blocks.id',
                'client_provider_blocks.client_id',
                'client_provider_blocks.provider_id',
                'client_provider_blocks.created_at',
                'client_provider_blocks.updated_at',
                'provider_user.name as provider_name',
                'provider_user.email as provider_email',
                'provider_user.phone as provider_phone',
                'providers.gender',
                'providers.average_rating as provider_rating',
                'provider_address.district as provider_district',
            )
            ->orderBy('client_provider_blocks.created_at', 'desc')
            ->get();
    }

    public function create(array $data): ClientProviderBlock
    {
        $existing = ClientProviderBlock::where('client_id', data_get($data, 'client_id'))
            ->where('provider_id', data_get($data, 'provider_id'))
            ->first();

        if ($existing) {
            if ($existing->trashed()) {
                $existing->restore();
                $existing->load(['provider.user']);

                return $existing;
            } else {
                throw new Exception(__('validation.client_provider_block.already_blocked'));
            }
        }

        $block = ClientProviderBlock::create($data);

        $block->load(['provider.user']);

        return $block;
    }

    public function delete(int $id): bool
    {
        $block = ClientProviderBlock::findOrFail($id);

        return $block->delete();
    }

    //

    public function getBlockedProviderIds(int $clientId): array
    {
        return ClientProviderBlock::where('client_id', $clientId)
            ->pluck('provider_id')
            ->toArray();
    }
}
