<?php

namespace Modules\User\Repositories;

use Illuminate\Database\Eloquent\Collection;
use Modules\User\Entities\Heir;
use Modules\User\Repositories\Contracts\HeirRepositoryInterface;

class HeirRepository implements HeirRepositoryInterface
{
    protected function baseQuery()
    {
        return Heir::query()
            ->where('user_id', auth()->id())
            ->orderBy('name');
    }

    public function getAllPaginated(int $perPage = 10, string $search = '')
    {
        $query = $this->baseQuery();

        return $query->paginate($perPage);
    }

    // public function getAllWithRelationsPaginated(
    //     int $perPage = 10,
    //     string $search = '',
    //     string $sortBy = 'name',
    //     string $sortOrder = 'asc'
    // ) {
    //     $allowedSortColumns = [
    //         'id',
    //         'name',
    //         'job_title',
    //         'relationship',
    //         'phone_number',
    //         'address',
    //         'is_primary',
    //         'created_at',
    //     ];
    //     $sortBy = in_array($sortBy, $allowedSortColumns, true) ? $sortBy : 'company_name';
    //     $sortOrder = strtolower($sortOrder) === 'desc' ? 'desc' : 'asc';

    //     $query = Employment::query()
    //             ->where('user_id', auth()->id())
    //             ->with(['user:id,name,email'])
    //             ->orderBy($sortBy, $sortOrder);

    //     return $query->paginate($perPage);
    // }

    public function getAllWithRelations(string $search = ''): Collection
    {
        $query = Heir::query()
                ->where('user_id', auth()->id())
                ->with(['user:id,name,email'])
                ->orderBy('name');

        return $query->get();
    }

    public function create(array $data): Heir
    {
        return Heir::create($data);
    }

    public function findById(string $id): ?Heir
    {
        return Heir::query()
            ->where('user_id', auth()->id())
            ->with(['user:id,name,email'])
            ->find($id);
    }

    public function delete(string $id): bool
    {
        $heir = $this->findById($id);
        if ($heir) {
            return $heir->delete();
        }

        return false;
    }

    public function all(string $search = ''): Collection
    {
        return $this->baseQuery()->get();
    }
}
