<?php

namespace App\Jobs\Posts;

use App\Models\Artwork;
use App\Models\Post;
use App\Models\PostTarget;
use App\Models\User;
use App\Services\Posts\PostHashtagService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * Creates a feed post of type=upload when an artwork is published.
 * Dispatched from ArtworkObserver when auto_post_upload is enabled for the user.
 */
class AutoUploadPostJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;

    public function __construct(
        public readonly int $artworkId,
        public readonly int $userId,
    ) {}

    public function handle(PostHashtagService $hashtagService): void
    {
        $artwork = Artwork::find($this->artworkId);
        $user    = User::find($this->userId);

        if (! $artwork || ! $user) {
            return;
        }

        // If post already exists for this artwork, skip (idempotent)
        $exists = Post::where('user_id', $user->id)
            ->where('type', Post::TYPE_UPLOAD)
            ->whereHas('targets', fn ($q) => $q->where('target_type', 'artwork')->where('target_id', $artwork->id))
            ->exists();

        if ($exists) {
            return;
        }

        DB::transaction(function () use ($artwork, $user, $hashtagService) {
            $post = Post::create([
                'user_id'    => $user->id,
                'type'       => Post::TYPE_UPLOAD,
                'visibility' => Post::VISIBILITY_PUBLIC,
                'body'       => null,
                'status'     => Post::STATUS_PUBLISHED,
            ]);

            PostTarget::create([
                'post_id'     => $post->id,
                'target_type' => 'artwork',
                'target_id'   => $artwork->id,
            ]);
        });

        Log::info("AutoUploadPostJob: created upload post for artwork #{$this->artworkId} by user #{$this->userId}");
    }
}
