<?php

namespace App\Services;

use App\Models\ClientPaymentMethod;
use Illuminate\Support\Collection;

class ClientPaymentMethodService
{
    public function getByClientId(int $clientId): Collection
    {
        return ClientPaymentMethod::where('client_id', $clientId)
            ->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
    {
        if ($data['is_active'] ?? true) {
            $this->deactivateOtherCards($data['client_id']);
        }

        return ClientPaymentMethod::create($data);
    }

    public function update(ClientPaymentMethod $paymentMethod, array $data): ClientPaymentMethod
    {
        if (isset($data['is_active']) && $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]);
    }
}
