<?php

namespace Database\Seeders;

use App\Models\Asset;
use App\Models\AssetAssignment;
use App\Models\AssetCategory;
use App\Models\User;
use Illuminate\Database\Seeder;

class AssetSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $computer = AssetCategory::updateOrCreate(['name' => 'Computer'], ['description' => 'Laptops, Desktops, and Servers']);
        $peripherals = AssetCategory::updateOrCreate(['name' => 'Peripherals'], ['description' => 'Keyboards, Mice, Monitors']);

        $assets = [
            ['category_id' => $computer->id, 'name' => 'MacBook Pro M3', 'serial' => 'MBP-2024-001'],
            ['category_id' => $computer->id, 'name' => 'Mac Mini M2', 'serial' => 'MM-2023-042'],
            ['category_id' => $peripherals->id, 'name' => 'Magic Keyboard', 'serial' => 'MK-772'],
            ['category_id' => $peripherals->id, 'name' => 'Dell 27" 4K Monitor', 'serial' => 'MON-DELL-991'],
        ];

        $employees = User::where('type', 'employee')->limit(4)->get();

        foreach ($assets as $index => $assetData) {
            $asset = Asset::updateOrCreate(
                ['serial_number' => $assetData['serial']],
                [
                    'category_id' => $assetData['category_id'],
                    'name' => $assetData['name'],
                    'purchase_date' => now()->subYear(),
                    'warranty_expiry' => now()->addYear(),
                    'condition' => 'good',
                    'status' => 'assigned',
                ]
            );

            if (isset($employees[$index])) {
                AssetAssignment::updateOrCreate(
                    ['asset_id' => $asset->id, 'returned_at' => null],
                    [
                        'user_id' => $employees[$index]->id,
                        'assigned_at' => now()->subMonths(6),
                    ]
                );
            }
        }
    }
}
