<?php

namespace Database\Seeders;

use App\Models\User;
use App\Modules\Core\Support\CompanyPermissionCatalog;
use App\Modules\Subscription\Models\Feature;
use App\Modules\Subscription\Models\Plan;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class SaasCoreSeeder extends Seeder
{
    public function run(): void
    {
        $this->seedRolesAndPermissions();
        $this->seedPlansAndFeatures();
        $this->seedSuperAdmin();
    }

    private function seedRolesAndPermissions(): void
    {
        $permissions = array_merge([
            'super-admin.access',
            'companies.manage',
            'plans.manage',
        ], CompanyPermissionCatalog::all());

        foreach ($permissions as $permission) {
            Permission::query()->firstOrCreate([
                'name' => $permission,
                'guard_name' => 'web',
            ]);
        }

        $superAdmin = Role::query()->firstOrCreate([
            'name' => 'super-admin',
            'guard_name' => 'web',
        ]);
        $superAdmin->syncPermissions($permissions);

        foreach (['company-owner', 'company-admin', 'company-member'] as $role) {
            Role::query()->firstOrCreate([
                'name' => $role,
                'guard_name' => 'web',
            ]);
        }
    }

    private function seedPlansAndFeatures(): void
    {
        $features = collect([
            ['name' => 'Invoice', 'slug' => 'invoice', 'module' => 'Invoice'],
            ['name' => 'POS', 'slug' => 'pos', 'module' => 'POS'],
            ['name' => 'Inventory', 'slug' => 'inventory', 'module' => 'Inventory'],
            ['name' => 'Accounting', 'slug' => 'accounting', 'module' => 'Accounting'],
            ['name' => 'Reports', 'slug' => 'reports', 'module' => 'Reports'],
            ['name' => 'CRM', 'slug' => 'crm', 'module' => 'CRM'],
            ['name' => 'Notification', 'slug' => 'notification', 'module' => 'Notification'],
            ['name' => 'AI Assistant', 'slug' => 'ai', 'module' => 'AI'],
        ])->mapWithKeys(function (array $feature): array {
            $model = Feature::query()->updateOrCreate(
                ['slug' => $feature['slug']],
                [
                    'name' => $feature['name'],
                    'module' => $feature['module'],
                    'is_active' => true,
                ]
            );

            return [$feature['slug'] => $model->id];
        });

        $plans = [
            'starter' => [
                'data' => [
                    'name' => 'Starter',
                    'description' => 'Invoice module for small businesses.',
                    'monthly_price' => 990,
                    'yearly_price' => 9900,
                    'trial_days' => 14,
                    'max_users' => 3,
                    'max_branches' => 1,
                    'is_active' => true,
                ],
                'features' => ['invoice'],
            ],
            'business' => [
                'data' => [
                    'name' => 'Business',
                    'description' => 'Invoice, POS, inventory, accounting, notifications, and reports.',
                    'monthly_price' => 2490,
                    'yearly_price' => 24900,
                    'trial_days' => 14,
                    'max_users' => 10,
                    'max_branches' => 3,
                    'is_active' => true,
                ],
                'features' => ['invoice', 'pos', 'inventory', 'accounting', 'reports', 'notification'],
            ],
            'enterprise' => [
                'data' => [
                    'name' => 'Enterprise',
                    'description' => 'All modules with advanced SaaS controls.',
                    'monthly_price' => 5990,
                    'yearly_price' => 59900,
                    'trial_days' => 30,
                    'max_users' => null,
                    'max_branches' => null,
                    'is_active' => true,
                ],
                'features' => ['invoice', 'pos', 'inventory', 'accounting', 'reports', 'crm', 'notification', 'ai'],
            ],
        ];

        foreach ($plans as $slug => $planConfig) {
            $plan = Plan::query()->updateOrCreate(
                ['slug' => $slug],
                $planConfig['data']
            );

            $plan->features()->sync($features->only($planConfig['features'])->values()->all());
        }
    }

    private function seedSuperAdmin(): void
    {
        $email = env('BIZNOVIA_SUPER_ADMIN_EMAIL', 'admin@biznovia.test');
        $password = env('BIZNOVIA_SUPER_ADMIN_PASSWORD', 'password');

        $user = User::query()->updateOrCreate(
            ['email' => $email],
            [
                'name' => env('BIZNOVIA_SUPER_ADMIN_NAME', 'BizNovia Admin'),
                'password' => Hash::make($password),
                'email_verified_at' => now(),
            ]
        );

        $user->assignRole('super-admin');
    }
}
