<?php

namespace App\Console\Commands;

use App\Models\Transaction;
use App\Models\TransactionType;
use Cog\Laravel\Love\ReactionType\Models\ReactionType as LoveReactionType;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class AddLoveReactionsToTransactions extends Command
{
    protected $signature = 'love:add-reactions-to-transactions';
    protected $description = 'Add Love Reaction to each from_account and to_account accountable with the transaction_type name as the reaction type';

    public function handle()
    {
        $transactions = Transaction::with(['accountFrom.accountable', 'accountTo.accountable', 'transactionType'])->get();
        $count = 0;

        $this->info('Adding love Reactions to each transaction. Please wait, this can take a while...');

        foreach ($transactions as $transaction) {
            $reactionTypeName = $transaction->transactionType->name ?? null;
            if (!$reactionTypeName) {
                Log::warning("Transaction {$transaction->id} has no transaction type name. Type is set to Work as a fallback");
                $reactionTypeName = 'Work';
            }

            // Check if reaction type exists in love_reaction_types
            if (!LoveReactionType::where('name', $reactionTypeName)->exists()) {
                Log::warning("ReactionType '{$reactionTypeName}' does not exist for transaction {$transaction->id}.");
                continue;
            }

            $fromAccountable = $transaction->accountFrom->accountable ?? null;
            $toAccountable = $transaction->accountTo->accountable ?? null;
            Log::info("Transaction {$transaction->id}: fromAccountable=" . ($fromAccountable ? get_class($fromAccountable) . ':' . $fromAccountable->id : 'null') . ", toAccountable=" . ($toAccountable ? get_class($toAccountable) . ':' . $toAccountable->id : 'null'));

            try {
                if ($fromAccountable && $toAccountable) {
                    Log::info("Transaction {$transaction->id}: Adding reaction '{$reactionTypeName}' from {$fromAccountable->id} to {$toAccountable->id}.");
                    $fromAccountable->viaLoveReacter()->reactTo($toAccountable, $reactionTypeName);
                    Log::info("Transaction {$transaction->id}: Adding reaction '{$reactionTypeName}' from {$toAccountable->id} to {$fromAccountable->id}.");
                    $toAccountable->viaLoveReacter()->reactTo($fromAccountable, $reactionTypeName);
                    $count++;
                } else {
                    Log::warning("Transaction {$transaction->id}: Missing fromAccountable or toAccountable.");
                }
            } catch (\Exception $e) {
                Log::error("Error adding reaction for transaction {$transaction->id}: " . $e->getMessage());
            }
        }

        $this->info("Added reactions for {$count} transactions.");
    }
}