<?php

namespace Database\Seeders;

use App\Models\AllocationRule;
use App\Models\CashRegister;
use App\Models\Company;
use App\Models\Location;
use App\Models\User;
use App\Services\LocationInventoryService;
use App\Services\LocationService;
use Illuminate\Database\Seeder;

class MultiStoreSeeder extends Seeder
{
    public function run(): void
    {
        $company = app(LocationService::class)->ensureCompanyAndDefaults();

        $store = Location::defaultStore();
        $warehouse = Location::centralWarehouse();

        if ($store && $warehouse) {
            // Default allocation rules (Split Orders ON for multi-branch carts)
            $rules = [
                ['name' => 'Store Preference', 'rule_type' => AllocationRule::TYPE_STORE_PREFERENCE, 'priority' => 10],
                ['name' => 'Nearest Store', 'rule_type' => AllocationRule::TYPE_NEAREST_STORE, 'priority' => 30],
                ['name' => 'Highest Stock', 'rule_type' => AllocationRule::TYPE_HIGHEST_STOCK, 'priority' => 40],
                ['name' => 'Priority Store', 'rule_type' => AllocationRule::TYPE_PRIORITY_STORE, 'priority' => 50],
                ['name' => 'Warehouse Fallback', 'rule_type' => AllocationRule::TYPE_WAREHOUSE_FALLBACK, 'priority' => 90],
                ['name' => 'Split Orders', 'rule_type' => AllocationRule::TYPE_SPLIT_ORDERS, 'priority' => 100, 'is_active' => true],
                ['name' => 'Back Orders', 'rule_type' => AllocationRule::TYPE_BACKORDERS, 'priority' => 110, 'is_active' => false],
            ];

            foreach ($rules as $rule) {
                AllocationRule::updateOrCreate(
                    [
                        'company_id' => $company->id,
                        'rule_type' => $rule['rule_type'],
                    ],
                    [
                        'name' => $rule['name'],
                        'priority' => $rule['priority'],
                        'is_active' => $rule['is_active'] ?? true,
                        'config' => [],
                    ]
                );
            }

            // Ensure Split Orders stays enabled for existing installs when re-seeded
            AllocationRule::query()
                ->where('company_id', $company->id)
                ->where('rule_type', AllocationRule::TYPE_SPLIT_ORDERS)
                ->update(['is_active' => true]);

            CashRegister::firstOrCreate(
                ['location_id' => $store->id, 'name' => 'Main Counter'],
                ['code' => 'REG-1', 'is_active' => true]
            );

            // Assign all admin/staff users to default store
            User::query()
                ->whereIn('user_type', ['admin', 'staff'])
                ->each(function (User $user) use ($store) {
                    $user->stores()->syncWithoutDetaching([
                        $store->id => ['is_default' => true],
                    ]);
                    if (!$user->default_location_id) {
                        $user->update(['default_location_id' => $store->id]);
                    }
                });

            // Backfill inventory into default store
            app(LocationInventoryService::class)->backfillFromProductStock($store->id);
        }

        $this->command?->info('Multi-store foundation seeded: company, warehouse, default store, rules, inventory backfill.');
    }
}
