<?php

namespace App\Services;

use App\Models\ClientPaymentMethod;
use App\Services\Pagarme\PagarmeCardService;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class ClientPaymentMethodService
{
    public function __construct(
        private readonly PagarmeCardService $pagarmeCardService,
    ) {}

    public function getByClientId(int $clientId): Collection
    {
        return ClientPaymentMethod::where('client_id', $clientId)
            ->select(
                'id',
                'brand',
                'last_four_digits',
                'card_name',
                'holder_name'
            )
            ->orderBy('is_active', 'desc')
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public function findById(int $id): ?ClientPaymentMethod
    {
        return ClientPaymentMethod::find($id);
    }

    public function create(array $data): ClientPaymentMethod
    {
        return DB::transaction(function () use ($data) {
            if (data_get($data, 'is_active', true)) {
                $this->deactivateOtherCards(data_get($data, 'client_id'));
            }

            $paymentMethod = ClientPaymentMethod::create($data);

            $cardId = $this->pagarmeCardService->createCardForPaymentMethod($paymentMethod);

            if (empty($cardId)) {
                throw new \RuntimeException(__('messages.pagarme_card_save_failed'));
            }

            return $paymentMethod->fresh();
        });
    }

    public function update(ClientPaymentMethod $paymentMethod, array $data): ClientPaymentMethod
    {
        if (data_get($data, 'is_active') !== null && data_get($data, 'is_active')) {
            $this->deactivateOtherCards($paymentMethod->client_id, $paymentMethod->id);
        }

        $paymentMethod->update($data);

        return $paymentMethod->fresh();
    }

    public function delete(ClientPaymentMethod $paymentMethod): bool
    {
        return $paymentMethod->delete();
    }

    //

    private function deactivateOtherCards(int $clientId, ?int $exceptId = null): void
    {
        $query = ClientPaymentMethod::where('client_id', $clientId);

        if ($exceptId) {
            $query->where('id', '!=', $exceptId);
        }

        $query->update(['is_active' => false]);
    }
}
