<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\ArtworkAward;
use App\Models\Artwork;
use App\Models\User;

class ArtworkAwardPolicy
{
    /**
     * Admins bypass all checks.
     */
    public function before(User $user, string $ability): ?bool
    {
        if (method_exists($user, 'isAdmin') && $user->isAdmin()) {
            return true;
        }

        return null;
    }

    /**
     * Any authenticated user with a mature account may award any artwork
     * that isn't their own.
     * Returns false (→ 403 or 404 based on caller) when the check fails.
     */
    public function award(User $user, Artwork $artwork): bool
    {
        if (! $artwork->is_public || ! $artwork->is_approved) {
            return false;
        }

        if ($artwork->user_id === $user->id) {
            return false;
        }

        return $this->accountIsMature($user);
    }

    /**
     * The user may change a medal they already placed.
     */
    public function change(User $user, ArtworkAward $award): bool
    {
        return $user->id === $award->user_id;
    }

    /**
     * The user may remove a medal they already placed.
     */
    public function remove(User $user, ArtworkAward $award): bool
    {
        return $user->id === $award->user_id;
    }

    // -------------------------------------------------------------------------

    private function accountIsMature(User $user): bool
    {
        if (! $user->created_at) {
            return true; // cannot verify — allow
        }

        return $user->created_at->diffInDays(now()) >= 7;
    }
}
