<?php

namespace Tricks\Monitoring\Http\Controllers;

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

class LastUpdatedController
{
    use ValidatesRequests;

    /**
     * @return array<string,bool|int|null>
     */
    public function __invoke(Request $request, EloquentModels $eloquentModels): array
    {
        return [
            'data_was_updated_since_last_midnight' => self::dataWasUpdatedSinceLastMidnight($eloquentModels),
            'last_updated_date' => self::lastUpdatedDate($eloquentModels)?->unix(),
        ];
    }

    private static function lastUpdatedDate(EloquentModels $eloquentModels): ?Carbon
    {
        $collection = $eloquentModels::get();

        /** @var Carbon|null $lastUpdatedDate */
        $lastUpdatedDate = $collection
            ->filter(fn (Model $modelInstance) => $modelInstance->count() > 0)
            ->map(fn ($modelInstance) => $modelInstance->timestamps
                ? $modelInstance->latest('updated_at')->first()?->updated_at
                : Carbon::now()
            )
            ->sort(fn (Carbon $dateA, Carbon $dateB) => $dateA->timestamp < $dateB->timestamp)
            ->first();

        return $lastUpdatedDate;
    }

    public static function dataWasUpdatedSinceLastMidnight(EloquentModels $eloquentModels): bool
    {
        $lastUpdatedDate = self::lastUpdatedDate($eloquentModels);

        $lastMidnight = now()->createMidnightDate();

        $dataWasUpdatedInTheLast24Hours = false;

        if ($lastUpdatedDate) {
            $dataWasUpdatedInTheLast24Hours = $lastUpdatedDate->greaterThan($lastMidnight);
        }

        return $dataWasUpdatedInTheLast24Hours;
    }
}
