<?php

namespace Modules\Activity\Repositories;

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

class ActivityRepository implements ActivityRepositoryInterface
{
    protected array $defaultRelations = ['activityType', 'documents'];

    protected array $detailRelations = [
        'activityType',
        'documents',
        'reports.preparedBy:id,name,email',
    ];

    protected function baseQuery()
    {
        return Activity::query()
            ->with($this->defaultRelations)
            ->orderBy('start_datetime', 'desc');
    }

    protected function applySearch($query, string $search)
    {
        if ($search !== '') {
            $query->where(function ($q) use ($search) {
                $q->where('title', 'ILIKE', "%{$search}%")
                    ->orWhere('reference_number', 'ILIKE', "%{$search}%")
                    ->orWhere('organizer', 'ILIKE', "%{$search}%")
                    ->orWhere('location', '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 = 'title',
        string $sortOrder = 'asc'
    ) {
        $allowedSortColumns = [
            'id',
            'title',
            'reference_number',
            'start_datetime',
            'end_datetime',
            'organizer',
            'location',
            'is_active',
            'created_at',
        ];
        $sortBy = in_array($sortBy, $allowedSortColumns, true) ? $sortBy : 'start_datetime';
        $sortOrder = strtolower($sortOrder) === 'desc' ? 'desc' : 'asc';

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

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

    public function getIndexPaginated(
        int $perPage = 10,
        string $search = '',
        string $sortBy = 'start_datetime',
        string $sortOrder = 'desc'
    ) {
        $allowedSortColumns = [
            'id',
            'title',
            'reference_number',
            'start_datetime',
            'end_datetime',
            'organizer',
            'location',
            'is_active',
            'created_at',
        ];
        $sortBy = in_array($sortBy, $allowedSortColumns, true) ? $sortBy : 'start_datetime';
        $sortOrder = strtolower($sortOrder) === 'desc' ? 'desc' : 'asc';

        $query = Activity::query()
            ->with([
                'activityType',
                'galleryImages' => fn ($q) => $q->orderBy('created_at')->limit(1),
            ])
            ->withCount(['galleryImages', 'attachments'])
            ->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): Activity
    {
        return Activity::create($data);
    }

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

    public function findByIdWithRelations(string $id): ?Activity
    {
        return Activity::query()
            ->with($this->detailRelations)
            ->find($id);
    }

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

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

        return false;
    }

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

        return $query->get();
    }
}
