<?php

namespace Database\Seeders;

use App\Models\Client;
use App\Models\Domain;
use App\Models\Employee;
use App\Models\Invoice;
use App\Models\Project;
use App\Models\Server;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;

/**
 * Imports repo root data.json (clients, servers, domains, employees, invoices, projects).
 * Run: php artisan db:seed --class=ImportLegacyJsonSeeder
 */
class ImportLegacyJsonSeeder extends Seeder
{
    public function run(): void
    {
        $path = base_path('../data.json');
        if (! File::isReadable($path)) {
            $this->command?->warn('data.json not found at '.$path.' — skipped.');

            return;
        }

        /** @var array<string, mixed> $data */
        $data = json_decode(File::get($path), true);
        if (! is_array($data)) {
            return;
        }

        if (Client::query()->exists()) {
            $this->command?->info('Legacy JSON import skipped (clients table not empty).');

            return;
        }

        $clientMap = [];
        foreach ($data['clients'] ?? [] as $c) {
            $row = Client::query()->create([
                'name' => $c['name'] ?? '',
                'email' => $c['email'] ?? null,
                'company' => $c['company'] ?? null,
                'phone' => $c['phone'] ?? null,
                'address' => $c['address'] ?? null,
                'status' => $c['status'] ?? 'active',
                'notes' => $c['notes'] ?? null,
            ]);
            if (! empty($c['id'])) {
                $clientMap[(string) $c['id']] = $row->id;
            }
        }

        $serverMap = [];
        foreach ($data['servers'] ?? [] as $s) {
            $row = Server::query()->create([
                'name' => $s['name'] ?? '',
                'hostname' => $s['hostname'] ?? null,
                'ip_address' => $s['ipAddress'] ?? null,
                'provider' => $s['provider'] ?? null,
                'type' => $s['type'] ?? null,
                'specs' => $s['specs'] ?? null,
                'cost' => $s['cost'] ?? 0,
                'status' => $s['status'] ?? 'active',
                'renewal_date' => $s['renewalDate'] ?? null,
                'notes' => $s['notes'] ?? null,
            ]);
            if (! empty($s['id'])) {
                $serverMap[(string) $s['id']] = $row->id;
            }
        }

        foreach ($data['domains'] ?? [] as $d) {
            $sid = $d['associatedServerId'] ?? null;
            Domain::query()->create([
                'name' => $d['name'] ?? '',
                'registrar' => $d['registrar'] ?? null,
                'expiration_date' => $d['expirationDate'] ?? null,
                'auto_renew' => (bool) ($d['autoRenew'] ?? false),
                'server_id' => $sid && isset($serverMap[(string) $sid]) ? $serverMap[(string) $sid] : null,
                'status' => $d['status'] ?? 'active',
                'notes' => $d['notes'] ?? null,
            ]);
        }

        foreach ($data['employees'] ?? [] as $e) {
            Employee::query()->create([
                'name' => $e['name'] ?? '',
                'email' => $e['email'] ?? null,
                'role' => $e['role'] ?? '',
                'department' => $e['department'] ?? null,
                'phone' => $e['phone'] ?? null,
                'hire_date' => $e['hireDate'] ?? null,
                'salary' => $e['salary'] ?? 0,
                'status' => $e['status'] ?? 'active',
                'notes' => $e['notes'] ?? null,
            ]);
        }

        foreach ($data['invoices'] ?? [] as $inv) {
            $cid = $inv['clientId'] ?? null;
            Invoice::query()->create([
                'invoice_number' => $inv['invoiceNumber'] ?? ('INV-'.date('Y').'-tmp'),
                'client_id' => $cid && isset($clientMap[(string) $cid]) ? $clientMap[(string) $cid] : null,
                'date' => $inv['date'] ?? now()->toDateString(),
                'due_date' => $inv['dueDate'] ?? null,
                'items' => is_array($inv['items'] ?? null) ? $inv['items'] : [],
                'subtotal' => $inv['subtotal'] ?? 0,
                'tax' => $inv['tax'] ?? 0,
                'total' => $inv['total'] ?? 0,
                'status' => $inv['status'] ?? 'pending',
                'notes' => $inv['notes'] ?? null,
            ]);
        }

        foreach ($data['projects'] ?? [] as $p) {
            $cid = $p['clientId'] ?? null;
            Project::query()->create([
                'name' => $p['name'] ?? '',
                'client_id' => $cid && isset($clientMap[(string) $cid]) ? $clientMap[(string) $cid] : null,
                'category' => $p['category'] ?? '',
                'description' => $p['description'] ?? null,
                'price' => $p['price'] ?? 0,
                'status' => $p['status'] ?? 'planning',
                'progress' => (int) ($p['progress'] ?? 0),
                'start_date' => $p['startDate'] ?? null,
                'end_date' => $p['endDate'] ?? null,
                'deliverables' => is_array($p['deliverables'] ?? null) ? $p['deliverables'] : [],
            ]);
        }
    }
}
