<?php

namespace Modules\User\Repositories;

use Illuminate\Database\Eloquent\Collection;
use Modules\User\Entities\Employment;
use Modules\User\Repositories\Contracts\EmploymentRepositoryInterface;

class EmploymentRepository implements EmploymentRepositoryInterface
{
    protected function baseQuery()
    {
        return Employment::query()
            ->where('user_id', auth()->id())
            ->orderBy('company_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 = 'company_name',
        string $sortOrder = 'asc'
    ) {
        $allowedSortColumns = [
            'id',
            'company_name',
            'job_title',
            'employment_type',
            'salary',
            'start_date',
            'end_date',
            'is_current',
            '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 = Employment::query()
                ->where('user_id', auth()->id())
                ->with(['user:id,name,email'])
                ->orderBy('company_name');

        return $query->get();
    }

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

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

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

        return false;
    }

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