<?php

namespace Database\Seeders;

use App\Models\Module;
use App\Models\Plan;
use Illuminate\Database\Seeder;

class PlansSeeder extends Seeder
{
    public function run(): void
    {
        $allModuleIds = Module::pluck('id', 'key');

        $sort = 1;
        foreach (config('plans') as $slug => $data) {
            $plan = Plan::updateOrCreate(
                ['slug' => $slug],
                [
                    'name'                => $data['name'],
                    'description'         => $data['description'],
                    'price_monthly'       => $data['price_monthly'],
                    'price_yearly'        => $data['price_yearly'],
                    'currency'            => $data['currency'],
                    'max_employees'       => $data['max_employees'],
                    'max_services'        => $data['max_services'],
                    'max_bookings_month'  => $data['max_bookings_month'],
                    'max_branches'        => $data['max_branches'],
                    'is_active'           => true,
                    'is_featured'         => $data['is_featured'] ?? false,
                    'is_public'           => true,
                    'sort_order'          => $data['sort_order'] ?? $sort++,
                ]
            );

            $modules = $data['modules'] === 'all'
                ? $allModuleIds->all()
                : $allModuleIds->only($data['modules'])->all();

            $sync = collect($modules)->mapWithKeys(fn ($id) => [$id => ['is_enabled' => true]])->all();
            $plan->modules()->sync($sync);
        }
    }
}
