<?php

namespace App\Models;

use CodeIgniter\Model;

class RegisteredSystemModel extends Model
{
    protected $table = 'registered_systems';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    protected $allowedFields = [
        'license_id',
        'mac_hash',
        'ip_address',
        'hostname',
        'user_id',
        'status',
        'first_seen_at',
        'last_seen_at',
    ];
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    public static function hashMac(string $macAddress): string
    {
        return hash('sha256', strtoupper(trim($macAddress)));
    }

    public function findByMacHash(string $macHash, int $licenseId): ?array
    {
        return $this->where('mac_hash', $macHash)
                    ->where('license_id', $licenseId)
                    ->first();
    }

    public function countActiveByLicense(int $licenseId): int
    {
        return $this->where('license_id', $licenseId)
                    ->where('status', 'active')
                    ->countAllResults();
    }

    public function registerSystem(int $licenseId, string $macAddress, ?string $ipAddress = null, ?string $hostname = null, ?int $userId = null): array
    {
        $macHash = self::hashMac($macAddress);
        $existing = $this->findByMacHash($macHash, $licenseId);

        if ($existing) {
            $this->update($existing['id'], [
                'ip_address' => $ipAddress,
                'hostname' => $hostname,
                'user_id' => $userId,
                'last_seen_at' => date('Y-m-d H:i:s'),
                'status' => 'active',
            ]);

            return [
                'success' => true,
                'message' => 'System already registered',
                'system_id' => $existing['id'],
                'is_new' => false,
            ];
        }

        $newId = $this->insert([
            'license_id' => $licenseId,
            'mac_hash' => $macHash,
            'ip_address' => $ipAddress,
            'hostname' => $hostname,
            'user_id' => $userId,
            'status' => 'active',
            'first_seen_at' => date('Y-m-d H:i:s'),
            'last_seen_at' => date('Y-m-d H:i:s'),
        ]);

        return [
            'success' => true,
            'message' => 'System registered successfully',
            'system_id' => $newId,
            'is_new' => true,
        ];
    }

    public function revokeSystem(int $systemId): bool
    {
        return $this->update($systemId, ['status' => 'revoked']);
    }

    public function getSystemsByLicense(int $licenseId): array
    {
        return $this->where('license_id', $licenseId)
                    ->orderBy('last_seen_at', 'DESC')
                    ->findAll();
    }
}
