<?php

declare(strict_types=1);

namespace Tricks\LaravelTools\Http\Controllers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Tricks\LaravelTools\EloquentModels;

final class LastUpdatedController
{
    use ValidatesRequests;

    /**
     * @return array<string,bool|int|null>
     */
    public function __invoke(Request $request, EloquentModels $eloquentModels): array
    {
        $lastUpdatedDate = self::lastUpdatedDate($eloquentModels);

        return [
            'data_was_updated_since_last_midnight' => self::dataWasUpdatedSinceLastMidnight($lastUpdatedDate),
            'last_updated_date' => $lastUpdatedDate?->unix(),
        ];
    }

    public static function dataWasUpdatedSinceLastMidnight(?Carbon $lastUpdatedDate): bool
    {
        if ($lastUpdatedDate instanceof Carbon) {
            return $lastUpdatedDate->greaterThan(Carbon::createMidnightDate());
        }

        return false;
    }

    public static function lastUpdatedDate(EloquentModels $eloquentModels): ?Carbon
    {
        return $eloquentModels::get()
            ->filter(fn (Model $modelInstance): bool => $modelInstance::query()->exists())
            ->map(function (Model $modelInstance): Carbon {
                if ($modelInstance->usesTimestamps() === false) {
                    return Carbon::now();
                }
                $latest = $modelInstance::query()->latest($modelInstance::UPDATED_AT)->first();
                /** @var Carbon $carbon */
                $carbon = $latest->{$modelInstance::UPDATED_AT};

                return $carbon;
            })
            ->sort(fn (Carbon $dateA, Carbon $dateB): int => $dateA->timestamp < $dateB->timestamp ? -1 : 1)
            ->first();
    }
}
