<?php

declare(strict_types=1);

use App\Models\PaymentMethod;
use App\Models\Tenant;
use App\Models\User;
use Laravel\Sanctum\Sanctum;

beforeEach(function () {
    putenv('PAYMENT_MOCK=1');
    $this->tenant = Tenant::factory()->create();
    app()->instance('currentTenant', $this->tenant);
    $this->user = User::factory()->create(['tenant_id' => $this->tenant->id]);
    Sanctum::actingAs($this->user);

    $this->method = PaymentMethod::create([
        'tenant_id' => $this->tenant->id,
        'provider' => 'kcp',
        'display_name' => 'KCP Test',
        'is_active' => true,
        'sandbox_mode' => true,
    ]);
});

it('creates a payment (mock)', function () {
    $res = $this->withHeader('X-Tenant-ID', $this->tenant->id)->postJson('/api/v1/payments', [
        'payment_method_id' => $this->method->id,
        'order_ref' => 'test-order-001',
        'amount' => 10000,
    ]);
    $res->assertCreated()->assertJsonStructure(['data' => ['id', 'status', 'pg_tid']]);
    expect($res->json('data.status'))->toBe('authorized');
});

it('fetches payment status', function () {
    $createRes = $this->withHeader('X-Tenant-ID', $this->tenant->id)->postJson('/api/v1/payments', [
        'payment_method_id' => $this->method->id,
        'order_ref' => 'test-order-002',
        'amount' => 20000,
    ])->assertCreated();
    $id = $createRes->json('data.id');

    $this->withHeader('X-Tenant-ID', $this->tenant->id)
        ->getJson("/api/v1/payments/{$id}")
        ->assertOk()
        ->assertJsonPath('data.id', $id);
});

it('refunds an authorized payment', function () {
    $this->user->assignRole('tenant_admin');
    $createRes = $this->withHeader('X-Tenant-ID', $this->tenant->id)->postJson('/api/v1/payments', [
        'payment_method_id' => $this->method->id,
        'order_ref' => 'test-order-003',
        'amount' => 30000,
    ])->assertCreated();
    $id = $createRes->json('data.id');

    $this->withHeader('X-Tenant-ID', $this->tenant->id)
        ->postJson("/api/v1/payments/{$id}/refund", ['amount' => 30000])
        ->assertCreated()
        ->assertJsonPath('data.status', 'succeeded');
});
