<?php

namespace Modules\Activity\Repositories;

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

class ActivityReportRepository implements ActivityReportRepositoryInterface
{
    protected array $defaultRelations = ['activity', 'preparedBy:id,name,email'];

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

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

        $query = ActivityReport::query()
            ->with($this->defaultRelations)
            ->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): ActivityReport
    {
        return ActivityReport::create($data);
    }

    public function findById(string $id): ?ActivityReport
    {
        return ActivityReport::query()
            ->with($this->defaultRelations)
            ->find($id);
    }

    public function delete(string $id): bool
    {
        $report = ActivityReport::query()->find($id);

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

        return false;
    }

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

        return $query->get();
    }
}
