<?php

declare(strict_types=1);

namespace App\Services\NovaCards;

use App\Models\NovaCard;
use App\Models\NovaCardChallenge;
use App\Models\NovaCardChallengeEntry;
use App\Models\User;

class NovaCardChallengeService
{
    public function submit(User $user, NovaCardChallenge $challenge, NovaCard $card, ?string $note = null): NovaCardChallengeEntry
    {
        $entry = NovaCardChallengeEntry::query()->updateOrCreate([
            'challenge_id' => $challenge->id,
            'card_id' => $card->id,
        ], [
            'user_id' => $user->id,
            'status' => NovaCardChallengeEntry::STATUS_ACTIVE,
            'note' => $note,
        ]);

        $challenge->forceFill([
            'entries_count' => NovaCardChallengeEntry::query()->where('challenge_id', $challenge->id)->count(),
        ])->save();

        $card->forceFill([
            'challenge_entries_count' => NovaCardChallengeEntry::query()->where('card_id', $card->id)->count(),
            'last_engaged_at' => now(),
        ])->save();

        return $entry;
    }
}