<?php

namespace Database\Seeders;

use App\Models\Department;
use App\Models\PerformanceCard;
use App\Models\PerformanceCardResult;
use App\Models\PerformanceWallet;
use App\Models\SekayaValue;
use App\Models\User;
use Illuminate\Database\Seeder;

class PerformanceCardSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Get users to assign as assignees and creators
        $users = User::limit(3)->get();
        $productValues = SekayaValue::where('type', SekayaValue::TYPE_PERFORMANCE_CARD_PRODUCT)->get();

        // Create or get departments
        $departments = $this->createDepartments();

        // Create sample performance cards with their wallets
        $performanceCards = [
            [
                'department_name' => 'Water Quality Management',
                'project_manner' => PerformanceCard::PROJECT_MANNER_DEVELOPMENTAL,
                'goal' => 'Improve water quality standards across all distribution centers by implementing advanced filtration systems and regular testing protocols.',
                'results' => [
                    'Installed 15 new filtration systems',
                    'Reduced contamination incidents by 40%',
                    'Achieved 98% water quality compliance rate',
                ],
                'product_count' => 3,
                'assignee_count' => 2,
                'wallet' => [
                    'name' => 'Water Quality Improvement Initiative',
                    'start_date' => '2024-01-15',
                    'expected_end_date' => '2024-12-31',
                    'description' => 'Comprehensive water quality improvement program covering all distribution centers.',
                ],
            ],
            [
                'department_name' => 'Infrastructure Development',
                'project_manner' => PerformanceCard::PROJECT_MANNER_SUPPORT,
                'goal' => 'Provide technical support and maintenance for existing water infrastructure to ensure optimal performance and longevity.',
                'results' => [
                    'Completed maintenance on 25 water stations',
                    'Reduced system downtime by 35%',
                    'Improved water pressure in 80% of service areas',
                ],
                'product_count' => 2,
                'assignee_count' => 1,
                'wallet' => [
                    'name' => 'Infrastructure Support Program',
                    'start_date' => '2024-02-01',
                    'expected_end_date' => '2024-11-30',
                    'description' => 'Ongoing technical support and maintenance program for water infrastructure.',
                ],
            ],
            [
                'department_name' => 'Community Engagement',
                'project_manner' => PerformanceCard::PROJECT_MANNER_EMPOWERMENT,
                'goal' => 'Empower local communities with water management skills and knowledge to maintain sustainable water access.',
                'results' => [
                    'Trained 150 community members in water management',
                    'Established 10 community water committees',
                    'Distributed 500 water quality testing kits',
                ],
                'product_count' => 1,
                'assignee_count' => 3,
                'wallet' => [
                    'name' => 'Community Empowerment Initiative',
                    'start_date' => '2024-03-01',
                    'expected_end_date' => '2024-10-31',
                    'description' => 'Community-focused program to build local water management capacity.',
                ],
            ],
            [
                'department_name' => 'Strategic Planning',
                'project_manner' => PerformanceCard::PROJECT_MANNER_INVESTMENT,
                'goal' => 'Develop long-term investment strategies for water infrastructure expansion and modernization.',
                'results' => [
                    'Secured $2M in funding for infrastructure expansion',
                    'Identified 20 new strategic installation sites',
                    'Developed 5-year water access improvement plan',
                ],
                'product_count' => 4,
                'assignee_count' => 2,
                'wallet' => [
                    'name' => 'Strategic Investment Portfolio',
                    'start_date' => '2024-01-01',
                    'expected_end_date' => '2024-12-31',
                    'description' => 'Long-term investment strategy for water infrastructure development.',
                ],
            ],
            [
                'department_name' => 'Emergency Response',
                'project_manner' => PerformanceCard::PROJECT_MANNER_SUPPORT,
                'goal' => 'Establish rapid response capabilities for water emergencies and disaster relief operations.',
                'results' => [
                    'Deployed emergency water supplies to 5 crisis areas',
                    'Reduced emergency response time by 60%',
                    'Maintained 99.5% water availability during emergencies',
                ],
                'product_count' => 2,
                'assignee_count' => 1,
                'wallet' => [
                    'name' => 'Emergency Response Fund',
                    'start_date' => '2024-01-01',
                    'expected_end_date' => '2024-12-31',
                    'description' => 'Emergency response and disaster relief operations fund.',
                ],
            ],
        ];

        foreach ($performanceCards as $cardData) {
            // Get the department ID
            $departmentId = $departments[$cardData['department_name']];

            $performanceCard = PerformanceCard::create([
                'department_id' => $departmentId,
                'project_manner' => $cardData['project_manner'],
                'goal' => $cardData['goal'],
            ]);

            // Create the performance wallet for this card
            if ($users->count() > 0) {
                $creator = $users->random();
                PerformanceWallet::create([
                    'name' => $cardData['wallet']['name'],
                    'start_date' => $cardData['wallet']['start_date'],
                    'expected_end_date' => $cardData['wallet']['expected_end_date'],
                    'description' => $cardData['wallet']['description'],
                    'performance_card_id' => $performanceCard->id,
                    'created_by' => $creator->id,
                ]);
            }

            // Add results
            foreach ($cardData['results'] as $result) {
                PerformanceCardResult::create([
                    'performance_card_id' => $performanceCard->id,
                    'result' => $result,
                ]);
            }

            // Assign products
            if ($productValues->count() > 0) {
                $selectedProducts = $productValues->random(min($cardData['product_count'], $productValues->count()));
                $performanceCard->products()->attach($selectedProducts->pluck('id'));
            }

            // Assign users
            if ($users->count() > 0) {
                $selectedUsers = $users->random(min($cardData['assignee_count'], $users->count()));
                $performanceCard->assignees()->attach($selectedUsers->pluck('id'));
            }
        }
    }

    /**
     * Create departments and return name-to-ID mapping
     */
    private function createDepartments(): array
    {
        $departmentNames = [
            'Water Quality Management',
            'Infrastructure Development',
            'Community Engagement',
            'Strategic Planning',
            'Emergency Response',
        ];

        $departments = [];

        foreach ($departmentNames as $name) {
            $department = Department::firstOrCreate(
                ['name' => $name],
                ['description' => "Department responsible for {$name} operations"]
            );
            $departments[$name] = $department->id;
        }

        return $departments;
    }
}
