<?php

namespace Tests\Feature;

use Database\Seeders\PlansSeeder;
use Database\Seeders\PlanEntitlementsSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class FeatureGuardMiddlewareTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed(PlansSeeder::class);
        $this->seed(PlanEntitlementsSeeder::class);
        DB::table('users')->insert(['tg_id' => 'u1', 'created_at' => now(), 'updated_at' => now()]);
        $planId = DB::table('plans')->where('key','free')->value('id');
        DB::table('subscriptions')->insert(['user_id' => 1, 'plan_id' => $planId, 'status' => 'active', 'created_at'=>now(),'updated_at'=>now()]);
        // Reduce entitlements for tight testing
        DB::table('plan_entitlements')->where('plan_id',$planId)->where('key','valuations_per_month')->update(['int_value' => 1]);
        DB::table('plan_entitlements')->where('plan_id',$planId)->where('key','instant_push_per_day')->update(['int_value' => 1]);
    }

    public function test_pricecheck_quota_consumed(): void
    {
        $payload = [
            'input' => [ ['role'=>'user','content'=>'قیمت پژو ۲۰۶؟'] ],
            'response_format' => [ 'type' => 'json_object' ],
        ];
        $this->postJson('/api/ai/respond', $payload)->assertStatus(200);
        $this->postJson('/api/ai/respond', $payload)->assertStatus(403);
    }

    public function test_instant_push_quota_consumed(): void
    {
        // First call ok, second blocked
        $this->postJson('/api/admin/opportunities/push', ['ids' => []])->assertStatus(200);
        $this->postJson('/api/admin/opportunities/push', ['ids' => []])->assertStatus(403);
    }

    public function test_view_deals_guard_on_listing_saved_ads(): void
    {
        // free plan has INF for view_deals in seeder; set to 1 for test
        $planId = DB::table('plans')->where('key','free')->value('id');
        DB::table('plan_entitlements')->where('plan_id',$planId)->where('key','view_deals')->update(['int_value' => 1, 'json_value' => null]);
        $this->getJson('/api/user/saved_ads')->assertStatus(200);
        $this->getJson('/api/user/saved_ads')->assertStatus(403);
    }
}

