<?php

namespace Tests\Unit\Services;

use App\Models\Order;
use App\Services\PaymentService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class PaymentServiceTest extends TestCase
{
    use RefreshDatabase;

    private PaymentService $payments;

    protected function setUp(): void
    {
        parent::setUp();
        $this->payments = app(PaymentService::class);
    }

    private function orderWithPendingPayment(): Order
    {
        $order = Order::create([
            'order_number' => 'NYR-'.uniqid(), 'customer_name' => 'x', 'customer_phone' => 'x',
            'shipping_address' => 'x', 'shipping_city' => 'x', 'shipping_area' => 'x',
            'subtotal' => 1000, 'shipping_charge' => 0, 'grand_total' => 1000,
            'payment_method' => 'easypaisa', 'payment_status' => 'pending', 'order_status' => 'pending',
        ]);
        $order->payments()->create(['method' => 'easypaisa', 'amount' => 1000, 'status' => 'pending']);

        return $order;
    }

    public function test_approve_syncs_payment_and_order_status_together(): void
    {
        $admin = $this->admin();
        $order = $this->orderWithPendingPayment();
        $payment = $order->payments->first();

        $this->payments->approve($payment, $admin);

        $this->assertSame('paid', $payment->fresh()->status->value);
        $this->assertSame($admin->id, $payment->fresh()->verified_by);
        $this->assertNotNull($payment->fresh()->verified_at);
        $this->assertSame('paid', $order->fresh()->payment_status->value);
    }

    public function test_reject_syncs_payment_and_order_status_with_reason(): void
    {
        $admin = $this->admin();
        $order = $this->orderWithPendingPayment();
        $payment = $order->payments->first();

        $this->payments->reject($payment, $admin, 'Transaction ID does not match.');

        $this->assertSame('rejected', $payment->fresh()->status->value);
        $this->assertSame('Transaction ID does not match.', $payment->fresh()->notes);
        $this->assertSame('rejected', $order->fresh()->payment_status->value);
    }
}
