<?php

use App\Models\Artwork;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

uses(RefreshDatabase::class);

it('copies published_at into created_at when an artwork is published', function () {
    $user = User::factory()->create();

    $artwork = Artwork::factory()->unpublished()->create([
        'user_id' => $user->id,
        'created_at' => Carbon::parse('2026-03-01 10:00:00'),
        'updated_at' => Carbon::parse('2026-03-01 10:00:00'),
    ]);

    $publishedAt = Carbon::parse('2026-03-29 14:30:00');

    $artwork->forceFill([
        'published_at' => $publishedAt,
        'artwork_status' => 'published',
        'is_public' => true,
        'is_approved' => true,
    ])->save();

    $artwork->refresh();

    expect($artwork->created_at?->toDateTimeString())->toBe($publishedAt->toDateTimeString());
    expect(DB::table('user_statistics')->where('user_id', $user->id)->value('last_upload_at'))->toBe($publishedAt->toDateTimeString());
});

it('syncs created_at from published_at for existing artworks via command', function () {
    $artwork = Artwork::factory()->create([
        'created_at' => Carbon::parse('2026-03-01 10:00:00'),
        'updated_at' => Carbon::parse('2026-03-01 10:00:00'),
        'published_at' => Carbon::parse('2026-03-25 08:15:00'),
    ]);

    $exitCode = Artisan::call('artworks:sync-created-at');

    expect($exitCode)->toBe(0);

    $createdAt = DB::table('artworks')->where('id', $artwork->id)->value('created_at');
    expect(Carbon::parse($createdAt)->toDateTimeString())->toBe('2026-03-25 08:15:00');
});