<?php

namespace App\Models;

use App\Core\Database;
use App\Core\Security;

class User extends BaseModel
{
    protected static string $table = 'users';

    /**
     * Find user securely by email using Blind Index (HMAC-SHA256 Hash).
     */
    public static function findByEmail(string $email): ?array
    {
        $emailHash = Security::blindIndex($email);
        
        return Database::selectOne(
            "SELECT * FROM users WHERE email_hash = :hash LIMIT 1",
            ['hash' => $emailHash]
        );
    }

    /**
     * Create a new user securely (encrypting sensitive data and generating hashes).
     */
    public static function createSecure(array $data): string
    {
        // 1. Hash password
        $data['password'] = Security::hashPassword($data['password']);

        // 2. Generate blind index for email lookup
        $data['email_hash'] = Security::blindIndex($data['email']);

        // 3. Encrypt the email itself using AES-256-GCM
        $data['email'] = Security::encrypt($data['email']);

        // 4. Ensure default values if none provided
        $data['role'] = $data['role'] ?? 'admin';
        $data['status'] = $data['status'] ?? 'active';

        return self::create($data);
    }
}
