<?php

declare(strict_types=1);

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Tricks\LaravelTools\EloquentModels;
use Tricks\LaravelTools\Http\Controllers\LastUpdatedController;
use Workbench\Database\Factories\TestModelFactory;
use Workbench\Database\Factories\TestModelWithoutTimestampsFactory;

use function Pest\Laravel\getJson;
use function Pest\Laravel\travelBack;
use function Pest\Laravel\travelTo;

uses(RefreshDatabase::class);

test('detects updates since last midnight', function (): void {

    $response = getJson('api/tricks/last_updated');

    $response->assertJson([
        'data_was_updated_since_last_midnight' => false,
        'last_updated_date' => false,
    ]);

    $model = TestModelFactory::new()->createOne();

    getJson('api/tricks/last_updated')
        ->assertJson([
            'data_was_updated_since_last_midnight' => true,
            'last_updated_date' => $model->getAttribute('updated_at')->unix(),
        ]);

    expect(LastUpdatedController::lastUpdatedDate(new EloquentModels))
        ->not->toBeNull()
        ->unix()
        ->toBe($model->updated_at->unix());
});

test('detects when data was not updated lately', function (): void {
    travelTo(Carbon::yesterday());
    $model = TestModelFactory::new()->createOne();

    $lastUpdated = LastUpdatedController::lastUpdatedDate(new EloquentModels);

    expect($lastUpdated)
        ->not->toBeNull()
        ->unix()
        ->toBe($model->updated_at->unix());

    expect(LastUpdatedController::dataWasUpdatedSinceLastMidnight($lastUpdated))
        ->toBeFalse();
});

test('it filters out models with no data', function (): void {
    expect(LastUpdatedController::lastUpdatedDate(new EloquentModels))
        ->toBeNull();
});

test('it filters out models with no timestamps', function (): void {
    travelTo(Carbon::now()->subHour());
    $model = TestModelFactory::new()->createOne();
    travelBack();
    TestModelWithoutTimestampsFactory::new()->createOne();

    expect(LastUpdatedController::lastUpdatedDate(new EloquentModels))
        ->unix()
        ->toBe($model->updated_at->unix());
});
