<?php

namespace Modules\Activity\Repositories;

use Illuminate\Database\Eloquent\Collection;
use Modules\Activity\Entities\ActivityType;
use Modules\Activity\Repositories\Contracts\ActivityTypeRepositoryInterface;

class ActivityTypeRepository implements ActivityTypeRepositoryInterface
{
    protected function baseQuery()
    {
        return ActivityType::query()->orderBy('name');
    }

    protected function applySearch($query, string $search)
    {
        if ($search !== '') {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'ILIKE', "%{$search}%")
                    ->orWhere('code', 'ILIKE', "%{$search}%");
            });
        }

        return $query;
    }

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

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

    public function getAllWithRelationsPaginated(
        int $perPage = 10,
        string $search = '',
        string $sortBy = 'name',
        string $sortOrder = 'asc'
    ) {
        $allowedSortColumns = ['id', 'name', 'code', 'created_at'];
        $sortBy = in_array($sortBy, $allowedSortColumns, true) ? $sortBy : 'name';
        $sortOrder = strtolower($sortOrder) === 'desc' ? 'desc' : 'asc';

        $query = ActivityType::query()->orderBy($sortBy, $sortOrder);
        $this->applySearch($query, $search);

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

    public function getAllWithRelations(string $search = ''): Collection
    {
        $query = $this->baseQuery();
        $this->applySearch($query, $search);

        return $query->get();
    }

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

    public function findById(string $id): ?ActivityType
    {
        return ActivityType::query()->find($id);
    }

    public function delete(string $id): bool
    {
        $activityType = $this->findById($id);

        if ($activityType) {
            return $activityType->delete();
        }

        return false;
    }

    public function all(string $search = ''): Collection
    {
        $query = $this->baseQuery();
        $this->applySearch($query, $search);

        return $query->get();
    }
}
