<?php

namespace App\Repositories;

use App\Models\Website;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;

class WebsiteRepository
{
    public function paginateForIndex(array $filters, int $perPage = 12): LengthAwarePaginator
    {
        return Website::query()
            ->with(['agent', 'siteHealthLogs' => fn ($query) => $query->limit(1)])
            ->when($filters['search'] ?? null, function ($query, $search) {
                $query->where(function ($builder) use ($search) {
                    $builder
                        ->where('name', 'like', "%{$search}%")
                        ->orWhere('domain', 'like', "%{$search}%");
                });
            })
            ->when($filters['status'] ?? null, fn ($query, $status) => $query->where('status', $status))
            ->orderByDesc('last_seen_at')
            ->orderBy('name')
            ->paginate($perPage)
            ->withQueryString();
    }

    public function create(array $data): Website
    {
        return Website::query()->create($data)->load('agent');
    }

    public function findForDetail(Website $website): Website
    {
        return $website
            ->load([
                'agent',
                'createdBy',
                'siteHealthLogs' => fn ($query) => $query->latest('checked_at')->limit(10),
                'apiAgentLogs' => fn ($query) => $query->latest('logged_at')->limit(12),
            ])
            ->loadCount(['tableSnapshots', 'backups', 'activityLogs']);
    }

    public function search(?string $term, int $limit = 8): Collection
    {
        if (! $term) {
            return new Collection();
        }

        return Website::query()
            ->with('agent')
            ->where(function ($query) use ($term) {
                $query
                    ->where('name', 'like', "%{$term}%")
                    ->orWhere('domain', 'like', "%{$term}%");
            })
            ->limit($limit)
            ->get();
    }

    public function update(Website $website, array $data): Website
    {
        $website->update($data);

        return $website->fresh(['agent']);
    }
}
