<?php

namespace Tests\Feature;

use App\Models\Feature;
use App\Models\Plan;
use App\Models\Service;
use App\Models\Tenant;
use App\Models\TenantFeatureOverride;
use App\Models\User;
use App\Models\WorkflowStage;
use App\Services\BillingService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class PlatformSuperAdminTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed();
    }

    public function test_platform_super_admin_can_access_platform_dashboard(): void
    {
        $admin = User::where('email', 'admin@platform.com')->first();
        $response = $this->actingAs($admin)->get('/platform/dashboard');
        $response->assertStatus(200);
    }

    public function test_platform_super_admin_can_edit_subscription_plan(): void
    {
        $admin = User::where('email', 'admin@platform.com')->firstOrFail();
        $plan = Plan::with('features')->firstOrFail();

        $this->actingAs($admin)->get(route('platform.plans.edit', $plan))
            ->assertOk()
            ->assertSee('Resource limits');

        $this->actingAs($admin)->put(route('platform.plans.update', $plan), [
            'name' => $plan->name,
            'description' => 'QC verified subscription plan',
            'price_monthly' => $plan->price_monthly,
            'price_yearly' => $plan->price_yearly,
            'max_users' => $plan->max_users + 1,
            'max_branches' => $plan->max_branches,
            'max_storage_gb' => $plan->max_storage_gb,
            'monthly_ai_credits' => $plan->monthly_ai_credits,
            'monthly_whatsapp_messages' => $plan->monthly_whatsapp_messages,
            'is_active' => 1,
            'features' => $plan->features->pluck('id')->all(),
        ])->assertRedirect(route('platform.plans'));

        $this->assertSame('QC verified subscription plan', $plan->fresh()->description);
    }

    public function test_tenant_users_are_blocked_from_accessing_platform_routes(): void
    {
        $tenantOwner = User::where('email', 'owner@almadina.ae')->first();
        $response = $this->actingAs($tenantOwner)->get('/platform/dashboard');
        $response->assertStatus(403);
    }

    public function test_tenant_creation_wizard_seeds_defaults_properly(): void
    {
        $admin = User::where('email', 'admin@platform.com')->first();
        $plan = Plan::first();

        $response = $this->actingAs($admin)->post('/platform/tenants', [
            'company_name' => 'New Star Typing LLC',
            'legal_name' => 'New Star Services LLC',
            'email' => 'info@newstartyping.ae',
            'mobile' => '+971501234567',
            'emirate' => 'Dubai',
            'owner_name' => 'Tariq Al Hashemi',
            'owner_email' => 'tariq@newstartyping.ae',
            'username' => 'tariq.admin',
            'password' => 'Password123!',
            'plan_id' => $plan->id,
            'billing_cycle' => 'monthly',
        ]);

        $response->assertRedirect();

        $tenant = Tenant::where('email', 'info@newstartyping.ae')->first();
        $this->assertNotNull($tenant);
        $this->assertEquals('New Star Typing LLC', $tenant->company_name);

        // Verify Owner user
        $owner = User::where('email', 'tariq@newstartyping.ae')->first();
        $this->assertNotNull($owner);
        $this->assertEquals($tenant->id, $owner->tenant_id);

        $starterService = Service::withoutGlobalScopes()
            ->where('tenant_id', $tenant->id)
            ->where('service_code', 'ICP-EID-NEW')
            ->firstOrFail();
        $this->assertGreaterThanOrEqual(8, Service::withoutGlobalScopes()->where('tenant_id', $tenant->id)->count());
        $this->assertTrue(WorkflowStage::where('service_id', $starterService->id)->where('stage_code', 'DELIVERED')->exists());
        $this->assertDatabaseHas('service_document_rules', ['tenant_id' => $tenant->id, 'service_id' => $starterService->id]);
    }

    public function test_tenant_feature_overrides_work_properly(): void
    {
        $tenant = Tenant::first();
        $feature = Feature::first();

        TenantFeatureOverride::create([
            'tenant_id' => $tenant->id,
            'feature_id' => $feature->id,
            'override_type' => 'deny',
        ]);

        $override = TenantFeatureOverride::where('tenant_id', $tenant->id)->where('feature_id', $feature->id)->first();
        $this->assertEquals('deny', $override->override_type);
    }

    public function test_manual_payment_recording_updates_invoice_balance(): void
    {
        $tenant = Tenant::first();
        $plan = Plan::first();
        $billingService = app(BillingService::class);

        $invoice = $billingService->generateSubscriptionInvoice($tenant, $plan);
        $this->assertEquals('issued', $invoice->status);
        $this->assertGreaterThan(0, $invoice->balance);

        $payment = $billingService->recordManualPayment($tenant, $invoice, (float) $invoice->total, 'bank_transfer', 'TRF-9900');

        $this->assertEquals('paid', $invoice->fresh()->status);
        $this->assertEquals(0, $invoice->fresh()->balance);
        $this->assertEquals('success', $payment->status);
    }
}
