<?php

namespace Database\Seeders;

use App\Models\AppSetting;
use App\Models\Device;
use App\Models\Employee;
use App\Models\Site;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

class DatabaseSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Seed the application's database with dev/demo data:
     * admin user, 5 sites + 1 device each (plaintext tokens printed + written
     * to DEVICE-TOKENS.txt), ~10 sample employees, and default app settings.
     */
    public function run(): void
    {
        AppSetting::current();

        User::query()->firstOrCreate(
            ['email' => 'admin@bth.local'],
            [
                'name' => 'Admin',
                'password' => 'password',
                'role' => 'admin',
                'site_id' => null,
                'email_verified_at' => now(),
            ]
        );

        $tokenLines = [];
        $tokenLines[] = 'AI Vision Attendance — Device Tokens (DEV ONLY, generated by DatabaseSeeder)';
        $tokenLines[] = 'Generated: '.now()->toDateTimeString();
        $tokenLines[] = str_repeat('=', 70);

        for ($i = 1; $i <= 5; $i++) {
            $site = Site::query()->firstOrCreate(
                ['name' => "Site {$i}"],
                ['address' => "Site {$i} Address"]
            );

            $plainToken = Str::random(64);

            $device = Device::query()->create([
                'site_id' => $site->id,
                'name' => "Site {$i} Door Camera",
                'token_hash' => hash('sha256', $plainToken),
                'config_version' => 1,
            ]);

            $line = "Site {$i} — device_id={$device->id} — token: {$plainToken}";
            $this->command?->info($line);
            $tokenLines[] = $line;
        }

        file_put_contents(base_path('DEVICE-TOKENS.txt'), implode(PHP_EOL, $tokenLines).PHP_EOL);
        $this->command?->info('Device tokens written to '.base_path('DEVICE-TOKENS.txt'));

        $names = [
            'EMP0001' => 'Ramesh Kumar',
            'EMP0002' => 'Suresh Patel',
            'EMP0003' => 'Anita Sharma',
            'EMP0004' => 'Priya Singh',
            'EMP0005' => 'Vikram Rao',
            'EMP0006' => 'Neha Gupta',
            'EMP0007' => 'Arjun Nair',
            'EMP0008' => 'Kavita Joshi',
            'EMP0009' => 'Manoj Verma',
            'EMP0010' => 'Deepa Iyer',
        ];

        $i = 0;
        foreach ($names as $empId => $name) {
            $i++;
            Employee::query()->firstOrCreate(
                ['emp_id' => $empId],
                [
                    'name' => $name,
                    'active' => true,
                    // First 8 employees have consent on file; last 2 do not (for enrollment/consent testing).
                    'consent_on' => $i <= 8 ? now()->subDays(30)->toDateString() : null,
                ]
            );
        }
    }
}
