<?php

namespace Tests\Feature;

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

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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'export_sub_test',
            'name' => '导出订阅测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 88,
            'list_price' => 88,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        SiteSubscription::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'status' => 'activated',
            'source' => 'manual',
            'subscription_no' => 'SUB_EXPORT_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => 'monthly',
            'period_months' => 1,
            'amount' => 88,
            'starts_at' => now()->subDays(1),
            'ends_at' => now()->addDays(29),
            'activated_at' => now()->subDays(1),
        ]);

        $res = $this->get('/admin/site-subscriptions/export?download=1');

        $res->assertOk();
        $res->assertHeader('content-type', 'text/csv; charset=UTF-8');

        $content = $res->streamedContent();
        $this->assertStringContainsString('订阅号', $content);
        $this->assertStringContainsString('SUB_EXPORT_0001', $content);
        $this->assertStringContainsString('到期时间', $content);
        $this->assertStringContainsString('到期状态', $content);
        $this->assertStringContainsString('关联订单数', $content);
        $this->assertStringContainsString('未到期', $content);

        // 状态导出应为“中文标签 + 原始值”
        $this->assertStringContainsString('已生效 (activated)', $content);
    }

    public function test_guest_cannot_export_site_subscriptions_csv(): void
    {
        $this->seed();

        $this->get('/admin/site-subscriptions/export')
            ->assertRedirect('/admin/login');
    }
}
