<?php

namespace App\Console\Commands;

use App\Models\Account;
use App\Models\Transaction;
use App\Traits\AccountInfoTrait;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MigrateCyclosGiftAccounts extends Command
{
    use AccountInfoTrait; // For using the getBalance() method

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'migrate:cyclos-gift-accounts';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This migrates balances from all "gift" accounts to the primary account of the same owner.';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $this->info('Starting gift account migration...');

        $giftAccounts = Account::where('name', 'gift')->get();

        if ($giftAccounts->isEmpty()) {
            $this->info('No gift accounts found.');
            return 0;
        }

        $this->info("Found {$giftAccounts->count()} gift accounts to process.");

        foreach ($giftAccounts as $fromAccount) {
            $this->line("Processing gift account ID: {$fromAccount->id} for owner: {$fromAccount->accountable->name}");

            // 1. Get the balance. If it's zero or less, there's nothing to do.
            $balance = $this->getBalance($fromAccount->id);
            if ($balance <= 0) {
                $this->line(" -> Balance is {$balance}. Nothing to migrate. Skipping.");
                continue;
            }
            $this->line(" -> Balance to migrate: " . tbFormat($balance));

            // 2. Find the destination account (the first non-gift account for the same owner)
            $toAccount = Account::where('accountable_id', $fromAccount->accountable_id)
                                ->where('accountable_type', $fromAccount->accountable_type)
                                ->where('name', '!=', 'gift')
                                ->first();

            if (!$toAccount) {
                $this->error(" -> No destination account found for owner ID {$fromAccount->accountable_id}. Skipping.");
                Log::warning("Gift Migration: No destination account for gift account ID {$fromAccount->id}");
                continue;
            }
            $this->line(" -> Destination account found: ID {$toAccount->id} ('{$toAccount->name}')");

            // 3. Prepare the transfer details
            $transactionTypeId = 6; // Migration type
            $description = "Migration of balance from gift account (ID: {$fromAccount->id})";

            // 4. Perform the database transaction
            DB::beginTransaction();
            try {
                $transfer = new Transaction();
                $transfer->from_account_id = $fromAccount->id;
                $transfer->to_account_id = $toAccount->id;
                $transfer->amount = $balance;
                $transfer->description = $description;
                $transfer->transaction_type_id = $transactionTypeId;
                $transfer->creator_user_id = null; // No user in a command context
                $transfer->save();

                DB::commit();
                $this->info(" -> SUCCESS: Migrated " . tbFormat($balance) . " to account ID {$toAccount->id}. Transaction ID: {$transfer->id}");
                Log::info("Gift Migration Success: Migrated {$balance} from account {$fromAccount->id} to {$toAccount->id}. TxID: {$transfer->id}");

            } catch (\Exception $e) {
                DB::rollBack();
                $this->error(" -> FAILED: An error occurred during the database transaction: " . $e->getMessage());
                Log::error("Gift Migration DB Error for account {$fromAccount->id}: " . $e->getMessage());
            }
        }

        // After the loop, mark all processed gift accounts as inactive
        $this->info('Marking all processed gift accounts as inactive...');
        $giftAccountIds = $giftAccounts->pluck('id');
        Account::whereIn('id', $giftAccountIds)->update(['inactive_at' => now()]);
        $this->info('All gift accounts have been marked as inactive.');

        $this->info('Gift account migration finished.');
        return 0;
    }
}