<?php

declare(strict_types=1);

namespace App\Repositories;

use App\Contracts\Repositories\OwnerPaymentAccountRepositoryInterface;
use App\Models\OwnerPaymentAccount;
use Illuminate\Support\Collection;

final class EloquentOwnerPaymentAccountRepository implements OwnerPaymentAccountRepositoryInterface
{
    public function create(array $data): OwnerPaymentAccount
    {
        return OwnerPaymentAccount::create($data);
    }

    public function update(int $id, array $data): OwnerPaymentAccount
    {
        $account = $this->find($id);
        $account->update($data);

        return $account->fresh();
    }

    public function delete(int $id): bool
    {
        return OwnerPaymentAccount::find($id)?->delete() ?? false;
    }

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

    public function getForOwner(int $ownerId): Collection
    {
        return OwnerPaymentAccount::forOwner($ownerId)
            ->orderBy('is_primary', 'desc')
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public function getPrimaryForOwner(int $ownerId): ?OwnerPaymentAccount
    {
        return OwnerPaymentAccount::forOwner($ownerId)
            ->primary()
            ->first();
    }

    public function unsetPrimaryForOwner(int $ownerId): void
    {
        OwnerPaymentAccount::forOwner($ownerId)
            ->update(['is_primary' => false]);
    }
}
