<?php

namespace App\Console\Commands;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Booking;
use Illuminate\Console\Command;

class FixExpiredBookingWithRefundedPaymentTransactionCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'expired_booking:fixExpiredPaymentTransaction';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Change the EXPIRED payment transaction of EXPIRED booking to REFUNDED if the payment transaction is fully refunded';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $bookings = Booking::where('status', ApprovalStatus::EXPIRED)->whereHas('transactions', function ($q) {
            $q->where('type', TransactionType::PAYMENT)->where('status', ApprovalStatus::EXPIRED)->whereHas('transactions', function ($q2) {
                $q2->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
            });
        })->get();

        foreach ($bookings as $booking) {
            $payment_transactions = $booking->transactions()->where('type', TransactionType::PAYMENT)->whereHas('transactions', function ($q2) {
                $q2->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
            })->get();

            foreach ($payment_transactions as $payment) {
                $payment_original_amount = $payment->original_amount;
                $refund_original_amount = $payment->transactions()->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->sum('original_amount');

                if ($payment_original_amount - $refund_original_amount < 0.01) {
                    $this->info("Updated booking id: $booking->id, payment transaction id: $payment->id, from EXPIRED to REFUNDED");

                    $payment->status = ApprovalStatus::REFUNDED;
                    $payment->save();
                }
            }
        }
    }
}
