<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class PlanEntitlementsSeeder extends Seeder
{
    public function run(): void
    {
        $map = [
            'free' => [
                'cities' => 1,
                'instant_push_per_day' => 0,
                'valuations_per_month' => 10,
                'view_deals' => 'INF',
            ],
            'member' => [
                'cities' => 1,
                'instant_push_per_day' => 1,
                'valuations_per_month' => 30,
                'view_deals' => 'INF',
            ],
            'pro' => [
                'cities' => 2,
                'instant_push_per_day' => 3,
                'valuations_per_month' => 100,
                'view_deals' => 'INF',
            ],
            'elite' => [
                'cities' => 5,
                'instant_push_per_day' => 10,
                'valuations_per_month' => 300,
                'view_deals' => 'INF',
            ],
        ];

        foreach ($map as $key => $ents) {
            $plan = DB::table('plans')->where('key', $key)->first();
            if (!$plan) {
                // Create placeholder plan rows if missing
                DB::table('plans')->insert([
                    'key' => $key,
                    'name' => ucfirst($key),
                    'amount_irr' => 0,
                    'duration_days' => 30,
                    'is_active' => true,
                    'created_at' => now(), 'updated_at' => now(),
                ]);
                $plan = DB::table('plans')->where('key', $key)->first();
            }
            foreach ($ents as $ekey => $val) {
                DB::table('plan_entitlements')->updateOrInsert([
                    'plan_id' => $plan->id,
                    'key' => $ekey,
                ], [
                    'int_value' => is_numeric($val) ? (int)$val : null,
                    'json_value' => is_numeric($val) ? null : json_encode($val),
                    'created_at' => now(), 'updated_at' => now(),
                ]);
            }
        }
    }
}
