<?php

namespace Database\Seeders;

use App\Models\Permission;
use App\Models\Plan;
use App\Models\Product;
use App\Models\Role;
use App\Models\SystemSetting;
use App\Models\User;
use App\Models\Vendor;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

/**
 * دیتای پیش‌فرض برای نصب تازه: دسترسی‌ها، پلن‌ها، وندور، نقش‌ها، ادمین، تنظیمات سیستم، چند محصول و مشتری نمونه.
 */
class DefaultDataSeeder extends Seeder
{
    public function run(): void
    {
        $this->call(PermissionsSeeder::class);
        $this->call(PlansSeeder::class);

        $vendor = Vendor::first();
        if (! $vendor) {
            $plan = Plan::where('slug', 'basic')->first();
            $vendor = Vendor::create([
                'name' => 'سازمان اصلی',
                'slug' => 'main',
                'plan_id' => $plan?->id,
            ]);
            $this->command->info('Vendor "main" created.');
        } else {
            $plan = Plan::where('slug', 'basic')->first();
            if ($plan && ! $vendor->plan_id) {
                $vendor->update(['plan_id' => $plan->id]);
                $this->command->info('Vendor plan set to Basic.');
            }
        }

        $adminRole = Role::withoutVendorScope()->firstOrCreate(
            ['vendor_id' => $vendor->id, 'name' => 'admin'],
            ['label' => 'مدیر سیستم']
        );

        $customerRole = Role::withoutVendorScope()->firstOrCreate(
            ['vendor_id' => $vendor->id, 'name' => 'customer'],
            ['label' => 'مشتری']
        );

        $adminRole->permissions()->sync(Permission::pluck('id'));

        $admin = User::withoutVendorScope()->firstOrCreate(
            ['vendor_id' => $vendor->id, 'username' => 'admin'],
            [
                'name' => 'مدیر سیستم',
                'password' => Hash::make('password'),
                'is_active' => true,
                'is_customer' => false,
            ]
        );

        $admin->roles()->syncWithoutDetaching([$adminRole->id]);

        $this->command->info('Admin user: username=admin / password=password (vendor: ' . $vendor->slug . ')');

        $this->seedDefaultSettings($vendor);
        $this->seedSampleProducts($vendor);
        $this->seedSampleCustomers($vendor, $customerRole);

        $this->call(SmsSettingsSeeder::class);
    }

    private function seedDefaultSettings(Vendor $vendor): void
    {
        $settings = [
            [
                'key' => 'company_name',
                'value' => 'سازمان اصلی',
                'type' => 'string',
                'description' => 'نام شرکت',
            ],
            [
                'key' => 'metal_precision',
                'value' => '3',
                'type' => 'number',
                'description' => 'دقت اعشار وزن فلز (گرم)',
            ],
            [
                'key' => 'currency_unit',
                'value' => 'RIAL',
                'type' => 'string',
                'description' => 'واحد پولی (RIAL یا TOMAN)',
            ],
        ];

        foreach ($settings as $s) {
            SystemSetting::withoutVendorScope()->updateOrCreate(
                ['vendor_id' => $vendor->id, 'key' => $s['key']],
                [
                    'value' => $s['value'],
                    'type' => $s['type'],
                    'description' => $s['description'] ?? null,
                ]
            );
        }

        $this->command->info('Default system settings created for vendor.');
    }

    private function seedSampleProducts(Vendor $vendor): void
    {
        if (Product::withoutVendorScope()->where('vendor_id', $vendor->id)->exists()) {
            return;
        }

        $products = [
            ['name' => 'نقره ساچمه عیار ۹۹۹', 'metal_type' => 'SILVER', 'purity' => 0.999],
            ['name' => 'نقره شمش عیار ۹۲۵', 'metal_type' => 'SILVER', 'purity' => 0.925],
            ['name' => 'طلا شمش عیار ۹۹۹', 'metal_type' => 'GOLD', 'purity' => 0.999],
        ];

        foreach ($products as $p) {
            Product::withoutVendorScope()->firstOrCreate(
                [
                    'vendor_id' => $vendor->id,
                    'metal_type' => $p['metal_type'],
                    'purity' => $p['purity'],
                ],
                [
                    'name' => $p['name'],
                    'current_stock_grams' => 0,
                ]
            );
        }

        $this->command->info('Sample products created.');
    }

    private function seedSampleCustomers(Vendor $vendor, Role $customerRole): void
    {
        $count = User::withoutVendorScope()
            ->where('vendor_id', $vendor->id)
            ->where('is_customer', true)
            ->count();

        if ($count > 0) {
            return;
        }

        $customers = [
            ['name' => 'مشتری نمونه ۱', 'mobile' => '09121234567'],
            ['name' => 'مشتری نمونه ۲', 'mobile' => '09129876543'],
        ];

        foreach ($customers as $c) {
            $user = User::withoutVendorScope()->firstOrCreate(
                [
                    'vendor_id' => $vendor->id,
                    'username' => $c['mobile'],
                ],
                [
                    'name' => $c['name'],
                    'mobile' => $c['mobile'],
                    'password' => Hash::make('password'),
                    'is_active' => true,
                    'is_customer' => true,
                ]
            );
            $user->roles()->syncWithoutDetaching([$customerRole->id]);
        }

        $this->command->info('Sample customers created.');
    }
}
