<?php

namespace Tests\Feature;

use App\Models\Category;
use App\Models\ServiceVendorMapping;
use App\Models\Transaction;
use App\Models\User;
use App\Models\Vendor;
use App\Models\Wallet;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class ElectricityMeterValidationTest extends TestCase
{
    use RefreshDatabase;

    public function test_electricity_meter_validation_endpoint_returns_customer_information(): void
    {
        Http::fake([
            'https://sandbox.vtpass.com/api/merchant-verify' => Http::response([
                'code' => '000',
                'content' => [
                    'Customer_Name' => 'Malam Muntari Abba',
                    'Address' => 'SHAGARI QTS KANTI KAZAURE',
                    'Meter_Number' => '30530328019',
                    'Meter_Type' => 'PREPAID',
                    'Minimum_Amount' => 100,
                    'Service' => 'kano-electric',
                ],
            ], 200),
        ]);

        $user = User::factory()->create();
        $category = Category::query()->create(['name' => 'Electricity', 'slug' => 'electricity']);
        $vendor = $this->seedVtpassVendor();

        ServiceVendorMapping::query()->create([
            'category_id' => $category->id,
            'network_id' => null,
            'vendor_id' => $vendor->id,
            'priority' => 1,
            'status' => 'active',
            'force_vendor' => false,
        ]);

        $response = $this->actingAs($user)
            ->get(route('app.buy.electricity.validate-meter', [
                'meter_number' => '30530328019',
                'disco_name' => 'kedco',
                'meter_type' => '1',
            ]));

        $response->assertOk()
            ->assertJsonPath('success', true)
            ->assertJsonPath('validation.customer_name', 'Malam Muntari Abba')
            ->assertJsonPath('validation.service_id', 'kano-electric');

        Http::assertSent(function ($request) {
            if ($request->url() !== 'https://sandbox.vtpass.com/api/merchant-verify') {
                return false;
            }

            $data = $request->data();

            return ($data['billersCode'] ?? null) === '30530328019'
                && ($data['serviceID'] ?? null) === 'kano-electric'
                && ($data['type'] ?? null) === 'prepaid';
        });
    }

    public function test_electricity_meter_validation_rejects_placeholder_customer_name(): void
    {
        Http::fake([
            'https://sandbox.vtpass.com/api/merchant-verify' => Http::response([
                'code' => '000',
                'response_description' => 'Validation successful',
                'content' => [
                    'Customer_Name' => '-',
                    'Meter_Number' => '45565754655',
                    'Meter_Type' => 'PREPAID',
                    'Service' => 'kano-electric',
                ],
            ], 200),
        ]);

        $user = User::factory()->create();
        $category = Category::query()->create(['name' => 'Electricity', 'slug' => 'electricity']);
        $vendor = $this->seedVtpassVendor();

        ServiceVendorMapping::query()->create([
            'category_id' => $category->id,
            'network_id' => null,
            'vendor_id' => $vendor->id,
            'priority' => 1,
            'status' => 'active',
            'force_vendor' => false,
        ]);

        $response = $this->actingAs($user)
            ->get(route('app.buy.electricity.validate-meter', [
                'meter_number' => '45565754655',
                'disco_name' => 'kedco',
                'meter_type' => '1',
            ]));

        $response->assertStatus(422)
            ->assertJsonPath('success', false);
    }

    public function test_electricity_purchase_accepts_optional_phone_number(): void
    {
        Http::fake([
            'https://sandbox.vtpass.com/api/pay' => Http::response([
                'code' => '000',
                'response_description' => 'TRANSACTION SUCCESSFUL',
                'content' => [
                    'transactions' => [
                        'status' => 'delivered',
                        'transactionId' => 'ELEC-TX-001',
                        'amount' => 1000,
                    ],
                ],
            ], 200),
        ]);

        $user = User::factory()->create();
        $user->setTransactionPin('1234');
        $user->save();
        Wallet::query()->create([
            'user_id' => $user->id,
            'balance' => 5000,
        ]);

        $category = Category::query()->create(['name' => 'Electricity', 'slug' => 'electricity']);
        $vendor = $this->seedVtpassVendor();

        ServiceVendorMapping::query()->create([
            'category_id' => $category->id,
            'network_id' => null,
            'vendor_id' => $vendor->id,
            'priority' => 1,
            'status' => 'active',
            'force_vendor' => false,
        ]);

        $response = $this->actingAs($user)
            ->post(route('app.buy.electricity.purchase'), [
                'category_slug' => 'electricity',
                'amount' => 1000,
                'meter_number' => '30530328019',
                'disco_name' => 'kedco',
                'meter_type' => '1',
                'transaction_pin' => '1234',
                // phone intentionally omitted
            ]);

        $response->assertSessionHasNoErrors()
            ->assertSessionHasNoErrors(['phone']);

        $transaction = Transaction::query()->latest('id')->first();
        $this->assertNotNull($transaction);
        $this->assertSame('success', $transaction->status);

        Http::assertSent(function ($request) {
            if ($request->url() !== 'https://sandbox.vtpass.com/api/pay') {
                return false;
            }

            $data = $request->data();

            return ! array_key_exists('phone', $data)
                && ($data['serviceID'] ?? null) === 'kano-electric'
                && ($data['billersCode'] ?? null) === '30530328019'
                && ($data['variation_code'] ?? null) === 'prepaid';
        });
    }

    protected function seedVtpassVendor(): Vendor
    {
        return Vendor::query()->create([
            'name' => 'VTPASS',
            'type' => 'vtpass',
            'base_url' => 'https://sandbox.vtpass.com',
            'auth_type' => 'token',
            'secret_encrypted' => 'unused',
            'vtpass_api_key' => 'api-key-test',
            'vtpass_public_key' => 'public-key-test',
            'vtpass_secret_key' => 'secret-key-test',
            'status' => 'active',
            'timeout_seconds' => 30,
        ]);
    }
}
