<?php

namespace App\Services\Posts;

use App\Models\Artwork;
use App\Models\Post;
use App\Models\PostTarget;
use App\Models\User;
use App\Services\ContentSanitizer;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class PostShareService
{
    /**
     * Share an artwork to a user's profile feed.
     *
     * Enforces:
     *  - artwork must be public
     *  - no duplicate share within 24 hours (for same user+artwork)
     *
     * @throws ValidationException
     */
    public function shareArtwork(
        User $user,
        Artwork $artwork,
        ?string $body,
        string $visibility = Post::VISIBILITY_PUBLIC,
    ): Post {
        // Ensure artwork is shareable
        if (! $artwork->is_public || ! $artwork->is_approved) {
            throw ValidationException::withMessages([
                'artwork_id' => ['This artwork cannot be shared because it is not publicly available.'],
            ]);
        }

        // Duplicate share prevention: same user + same artwork within 24h
        $alreadyShared = Post::where('user_id', $user->id)
            ->where('type', Post::TYPE_ARTWORK_SHARE)
            ->where('created_at', '>=', Carbon::now()->subHours(24))
            ->whereHas('targets', function ($q) use ($artwork) {
                $q->where('target_type', 'artwork')->where('target_id', $artwork->id);
            })
            ->exists();

        if ($alreadyShared) {
            throw ValidationException::withMessages([
                'artwork_id' => ['You already shared this artwork recently. Please wait 24 hours before sharing it again.'],
            ]);
        }

        $sanitizedBody = $body ? ContentSanitizer::render($body) : null;

        return DB::transaction(function () use ($user, $artwork, $sanitizedBody, $visibility) {
            $post = Post::create([
                'user_id'    => $user->id,
                'type'       => Post::TYPE_ARTWORK_SHARE,
                'visibility' => $visibility,
                'body'       => $sanitizedBody,
            ]);

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

            return $post;
        });
    }
}
