<?php

namespace App\Services;

use App\Models\ProviderClientBlock;
use Exception;

class ProviderClientBlockService
{
    public function getByProviderId(int $providerId)
    {
        return ProviderClientBlock::with(['client.user', 'client.profileMedia'])
            ->where('provider_id', $providerId)
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public function create(array $data): ProviderClientBlock
    {
        // Validar duplicidade (ignorando soft-deleted)

        $existing = ProviderClientBlock::where('provider_id', data_get($data, 'provider_id'))
            ->where('client_id', data_get($data, 'client_id'))
            ->first();

        if ($existing) {
            if ($existing->trashed()) {
                // Se foi deletado (desbloqueado), restaura

                $existing->restore();
                $existing->load(['client.user']);

                return $existing;
            } else {
                // Se já existe ativo, lança erro

                throw new Exception(__('validation.provider_client_block.already_blocked'));
            }
        }

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

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

        return $block;
    }

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

        return $block->delete();
    }

    //

    public function getBlockedClientIds(int $providerId): array
    {
        return ProviderClientBlock::where('provider_id', $providerId)
            ->pluck('client_id')
            ->toArray();
    }
}
