<?php

namespace Tests\Feature;

use App\Models\PlatformOrder;
use App\Models\SiteSubscription;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AdminPlatformOrderAttachSubscriptionShouldGuardTest extends TestCase
{
    use RefreshDatabase;

    protected function loginAsPlatformAdmin(): void
    {
        $this->seed();

        $this->post('/admin/login', [
            'email' => 'platform.admin@demo.local',
            'password' => 'Platform@123456',
        ])->assertRedirect('/admin');
    }

    public function test_attach_subscription_should_guard_non_renewal_orders(): void
    {
        $this->loginAsPlatformAdmin();

        $order = PlatformOrder::query()->create([
            'merchant_id' => 1,
            'plan_id' => 1,
            'order_no' => 'PO_TEST_ATTACH_1',
            'order_type' => 'new_purchase',
            'status' => 'placed',
            'payment_status' => 'unpaid',
            'payment_channel' => '',
            'plan_name' => 'Test',
            'billing_cycle' => 'monthly',
            'period_months' => 1,
            'quantity' => 1,
            'list_amount' => 0,
            'discount_amount' => 0,
            'payable_amount' => 0,
            'paid_amount' => 0,
            'meta' => [],
        ]);

        $sub = SiteSubscription::query()->firstOrFail();

        $res = $this->post("/admin/platform-orders/{$order->id}/attach-subscription", [
            'site_subscription_id' => $sub->id,
        ]);

        $res->assertRedirect();

        $order->refresh();
        $this->assertTrue((int) ($order->site_subscription_id ?? 0) === 0);
    }
}
