<?php

namespace Database\Seeders;

use App\Models\Department;
use App\Models\Dealer;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

class DepartmentSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $baselineNames = config('mtt_tenant_baseline.departments', [
            'Admin',
            'Executive',
            'Finance',
            'Inventory',
            'Marketing',
            'Operations',
            'Sales',
        ]);

        $definitions = [];
        foreach ($baselineNames as $name) {
            $definitions[] = [
                'code' => Str::slug($name, '_'),
                'name' => $name,
                'is_system' => true,
                'is_builtin' => true,
            ];
        }

        // System Administration remains a protected, built-in department but is not part of the dealer baseline list.
        $definitions[] = [
            'code' => 'system_administration',
            'name' => 'System Administration',
            'is_system' => true,
            'is_builtin' => true,
        ];

        foreach (Dealer::query()->get() as $dealer) {
            $departmentIdsByCode = [];

            foreach ($definitions as $definition) {
                if (($definition['name'] ?? null) === 'System Administration' && ! (bool) $dealer->is_default) {
                    // Skip System Administration for non-default dealers; it is platform-only.
                    continue;
                }

                $slug = Str::slug($definition['name']);

                $record = Department::query()
                    ->where('dealer_id', $dealer->id)
                    ->where(function ($query) use ($definition, $slug) {
                        $query->where('code', $definition['code'])
                              ->orWhere('slug', $slug);
                    })
                    ->first();

                if ($record) {
                    $record->name = $definition['name'];
                    $record->code = $definition['code'];
                    $record->slug = $slug;
                    $record->is_system = (bool) ($definition['is_system'] ?? false);
                    $record->is_builtin = (bool) ($definition['is_builtin'] ?? false);
                    $record->save();
                } else {
                    $record = Department::query()->create([
                        'dealer_id' => $dealer->id,
                        'name' => $definition['name'],
                        'code' => $definition['code'],
                        'slug' => $slug,
                        'is_system' => (bool) ($definition['is_system'] ?? false),
                        'is_builtin' => (bool) ($definition['is_builtin'] ?? false),
                    ]);
                }

                $departmentIdsByCode[$definition['code']] = $record->id;
            }

            // Map legacy department codes to the new one-word organizational codes.
            $legacyToCurrent = [
                'buyers' => 'inventory',
                'financial_manager' => 'finance',
                'fi' => 'finance',
                'recon' => 'operations',
            ];

            foreach ($legacyToCurrent as $legacyCode => $currentCode) {
                $targetDepartmentId = $departmentIdsByCode[$currentCode] ?? null;
                if (!$targetDepartmentId) {
                    continue;
                }

                $legacyDepartmentIds = Department::query()
                    ->where('dealer_id', $dealer->id)
                    ->where('code', $legacyCode)
                    ->pluck('id');

                if ($legacyDepartmentIds->isEmpty()) {
                    continue;
                }

                User::query()
                    ->whereIn('department_id', $legacyDepartmentIds)
                    ->update(['department_id' => $targetDepartmentId]);

                Department::query()->whereIn('id', $legacyDepartmentIds)->delete();
            }
        }
    }
}
