<?php

namespace Tests\Feature;

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

class AdminPlanSummaryStatsCountTest 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_plan_index_page_can_show_summary_stats_without_unknown_column_error(): void
    {
        $this->loginAsPlatformAdmin();

        $merchant = Merchant::query()->firstOrFail();

        $planA = Plan::query()->create([
            'code' => 'plan_summary_a',
            'name' => '套餐A',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $planB = Plan::query()->create([
            'code' => 'plan_summary_b',
            'name' => '套餐B',
            'billing_cycle' => 'monthly',
            'price' => 20,
            'list_price' => 20,
            'status' => 'active',
            'sort' => 20,
            'published_at' => now(),
        ]);

        SiteSubscription::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $planA->id,
            'subscription_no' => 'SUB_PLAN_SUMMARY_0001',
            'status' => 'active',
            'starts_at' => now(),
            'ends_at' => now()->addMonth(),
        ]);

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $planA->id,
            'order_no' => 'PO_PLAN_SUMMARY_0001',
            'order_type' => 'new_purchase',
            'status' => 'activated',
            'payment_status' => 'paid',
            'plan_name' => $planA->name,
            'billing_cycle' => $planA->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'paid_at' => now(),
            'activated_at' => now(),
            'meta' => [],
        ]);

        $this->get('/admin/plans')
            ->assertOk()
            ->assertSee('套餐管理')
            ->assertSee('1');
    }
}
