<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'mfa_secret',
        'mfa_recovery_codes',
        'mfa_enabled_at',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'mfa_recovery_codes' => 'array',
        'mfa_enabled_at' => 'datetime',
    ];

    /**
     * User roles relationship.
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'user_roles')
            ->using(UserRole::class)
            ->withTimestamps()
            ->withPivot(['expires_at', 'meta']);
    }

    /**
     * Build claims for apps and role grouping.
     */
    public function buildClaims(): array
    {
        $roles = $this->roles()->withPivot('expires_at', 'meta')->get();
        $now = now();
        $byApp = [];
        foreach ($roles as $role) {
            $expires = $role->pivot->expires_at ? $role->pivot->expires_at : null;
            if ($expires && $expires->lt($now)) {
                continue;
            }
            $byApp[$role->app][] = $role->key;
        }
        $apps = array_keys($byApp);
        $claims = [
            'sub' => $this->id,
            'email' => $this->email,
            'apps' => $apps,
        ];
        foreach ($byApp as $app => $keys) {
            $claims['roles_'.$app] = array_values(array_unique($keys));
        }
        return $claims;
    }

    /**
     * Check if user has any of the given role keys.
     *
     * @param array<int, string> $roleKeys
     */
    public function hasAnyRole(array $roleKeys): bool
    {
        $current = $this->roles()->pluck('key')->all();
        return !empty(array_intersect($roleKeys, $current));
    }

    /**
    * Generate recovery codes (8). Returns plain + hashed.
    *
    * @return array{plain: array<int, string>, hashed: array<int, string>}
    */
    public function generateRecoveryCodes(): array
    {
        $plain = [];
        $hashed = [];
        for ($i = 0; $i < 8; $i++) {
            $code = strtoupper(bin2hex(random_bytes(4))).'-'.strtoupper(bin2hex(random_bytes(2)));
            $plain[] = $code;
            $hashed[] = password_hash($code, PASSWORD_BCRYPT);
        }
        return ['plain' => $plain, 'hashed' => $hashed];
    }

    public function markRecoveryCodeUsed(string $code): void
    {
        $codes = $this->mfa_recovery_codes ?? [];
        $remaining = [];
        foreach ($codes as $stored) {
            if (!password_verify($code, $stored)) {
                $remaining[] = $stored;
            }
        }
        $this->mfa_recovery_codes = $remaining;
        $this->save();
    }

}
