<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Payment;
use App\Models\PaymentLink;

class ShowPayment extends Command
{
    /**
     * Usage:
     *   php artisan payment:show 123                # by payment ID
     *   php artisan payment:show 8e15...27bb        # by public_token
     */
    protected $signature = 'payment:show {value : Payment ID or PaymentLink public_token}';

    protected $description = 'Show payment details by ID or link token (auto-detected)';

    public function handle(): int
    {
        $value = trim((string) $this->argument('value'));

        $payment = null;

        // Heuristic: purely digits? probably an ID. Otherwise token.
        if (ctype_digit($value)) {
            $payment = Payment::find((int) $value);
            if (! $payment) {
                // Fallback: maybe someone stored numeric-ish tokens — try as token
                $payment = optional(PaymentLink::where('public_token', $value)->first())->payment;
            }
        } else {
            $payment = optional(PaymentLink::where('public_token', $value)->first())->payment;
            if (! $payment) {
                // Fallback: try as ID just in case
                $payment = Payment::find($value);
            }
        }

        if (! $payment) {
            $this->error("No payment found for value [{$value}].");
            $this->line('Tip: pass a numeric ID (e.g., 42) or a public token from /pay/{token}.');
            return self::FAILURE;
        }

        // Build a friendly link (if there is one)
        $link     = $payment->link()->first();
        $linkUrl  = $link ? url('/pay/' . $link->public_token) : null;

        $this->table(
            ['Field', 'Value'],
            [
                ['ID',            $payment->id],
                ['Type',          $payment->type ?? $payment->purpose ?? null],
                ['Amount cents',  $payment->amount_cents],
                ['Amount',        $payment->amount],
                ['Currency',      $payment->currency],
                ['Status',        $payment->status],
                ['Paid at',       $payment->paid_at],
                ['Job ID',        $payment->job_id ?? null],
                ['Booking ID',    $payment->booking_id ?? null],
                ['Customer ID',   $payment->customer_id ?? null],
                ['Pay URL',       $linkUrl ?? '(no link)'],
                ['Link token',    $link->public_token ?? '(no link)'],
            ]
        );

        return self::SUCCESS;
    }
}
