<?php

declare(strict_types=1);

use App\Models\Artwork;
use Illuminate\Support\Carbon;

require __DIR__ . '/../vendor/autoload.php';
$app = require __DIR__ . '/../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

$options = getopt('', ['id::', 'limit::']);
$id = isset($options['id']) ? (int) $options['id'] : null;
$limit = isset($options['limit']) ? max(1, (int) $options['limit']) : 5;

$query = Artwork::query()->orderByDesc('id');
if ($id && $id > 0) {
    $query->whereKey($id);
}

$rows = $query->limit($limit)->get();

if ($rows->isEmpty()) {
    fwrite(STDOUT, "No artwork rows found.\n");
    exit(1);
}

$requiredFields = [
    'title',
    'slug',
    'file_name',
    'file_path',
    'hash',
    'file_ext',
    'thumb_ext',
    'mime_type',
    'file_size',
    'published_at',
];

$hasFailure = false;

foreach ($rows as $artwork) {
    $missing = [];

    foreach ($requiredFields as $field) {
        $value = $artwork->{$field};
        if ($value === null || $value === '' || $value === 'pending') {
            $missing[] = $field;
        }
    }

    if (! (bool) $artwork->is_public) {
        $missing[] = 'is_public';
    }

    if (! (bool) $artwork->is_approved) {
        $missing[] = 'is_approved';
    }

    if ((int) $artwork->width <= 1) {
        $missing[] = 'width';
    }

    if ((int) $artwork->height <= 1) {
        $missing[] = 'height';
    }

    $publishedAt = $artwork->published_at instanceof Carbon
        ? $artwork->published_at->toDateTimeString()
        : (string) $artwork->published_at;

    fwrite(STDOUT, str_repeat('-', 72) . "\n");
    fwrite(STDOUT, "artwork_id: {$artwork->id}\n");
    fwrite(STDOUT, "title     : " . (string) $artwork->title . "\n");
    fwrite(STDOUT, "slug      : " . (string) $artwork->slug . "\n");
    fwrite(STDOUT, "file_path : " . (string) $artwork->file_path . "\n");
    fwrite(STDOUT, "hash      : " . (string) $artwork->hash . "\n");
    fwrite(STDOUT, "file_ext  : " . (string) $artwork->file_ext . " | thumb_ext: " . (string) $artwork->thumb_ext . "\n");
    fwrite(STDOUT, "visible   : is_public=" . ((int) (bool) $artwork->is_public) . " is_approved=" . ((int) (bool) $artwork->is_approved) . "\n");
    fwrite(STDOUT, "published : " . ($publishedAt !== '' ? $publishedAt : 'NULL') . "\n");

    if ($missing !== []) {
        $hasFailure = true;
        fwrite(STDOUT, "status    : FAIL (missing/invalid: " . implode(', ', array_unique($missing)) . ")\n");
    } else {
        fwrite(STDOUT, "status    : OK\n");
    }
}

fwrite(STDOUT, str_repeat('-', 72) . "\n");
if ($hasFailure) {
    fwrite(STDOUT, "Result: FAIL\n");
    exit(2);
}

fwrite(STDOUT, "Result: OK\n");
exit(0);
