<?php

namespace Database\Seeders;

use App\Models\AuditLog;
use App\Models\Event;
use App\Models\User;
use Illuminate\Database\Seeder;

class AuditLogSeeder extends Seeder
{
    public function run(): void
    {
        $admin = User::query()->where('email', 'admin@algaarena.gg')->first();
        $event = Event::query()->where('slug', 'alga-open-scrim-cup')->first();

        if (! $admin) {
            return;
        }

        $entries = [
            [
                'action' => 'event.published',
                'subject_type' => $event ? Event::class : null,
                'subject_id' => $event?->id,
                'new_values' => ['status' => 'registration_open'],
            ],
            [
                'action' => 'user.suspended',
                'subject_type' => User::class,
                'subject_id' => User::query()->where('email', 'nova@algaarena.gg')->value('id'),
                'old_values' => ['status' => 'active'],
                'new_values' => ['status' => 'suspended'],
            ],
            [
                'action' => 'user.reactivated',
                'subject_type' => User::class,
                'subject_id' => User::query()->where('email', 'nova@algaarena.gg')->value('id'),
                'old_values' => ['status' => 'suspended'],
                'new_values' => ['status' => 'active'],
            ],
            [
                'action' => 'settings.updated',
                'subject_type' => null,
                'subject_id' => null,
                'new_values' => ['auto_publish_records' => false],
            ],
        ];

        foreach ($entries as $index => $entry) {
            if ($entry['subject_id'] === null && filled($entry['subject_type'])) {
                continue;
            }

            AuditLog::updateOrCreate(
                [
                    'user_id' => $admin->id,
                    'action' => $entry['action'],
                    'subject_type' => $entry['subject_type'],
                    'subject_id' => $entry['subject_id'],
                ],
                [
                    'old_values' => $entry['old_values'] ?? null,
                    'new_values' => $entry['new_values'] ?? null,
                    'ip_address' => '127.0.0.1',
                    'user_agent' => 'Seeder/Demo',
                    'created_at' => now()->subDays(5 - $index),
                ],
            );
        }
    }
}
