<?php

namespace App\Models;

use App\Models\Traits\HasHexId;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasHexId {
        toArray as hexIdToArray;
    }
    use Notifiable;

    protected $table = 'users';
    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = ['id', 'name', 'display_name', 'email', 'password', 'organization_id', 'role_id'];

    public function getAuthIdentifier()
    {
        return $this->getAttributes()['id'] ?? $this->id;
    }

    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id', 'id');
    }

    public function organization()
    {
        return $this->belongsTo(Organization::class, 'organization_id', 'id');
    }

    public function hasRole(string $roleName): bool
    {
        if (isset($this->role) && is_object($this->role) && isset($this->role->name)) {
            if ($this->role->name === $roleName) {
                return true;
            }
        }

        $roleIdBin = $this->getAttributes()['role_id'] ?? null;
        if (!empty($roleIdBin)) {
            $r = Role::where('id', $roleIdBin)->first();
            if ($r && $r->name === $roleName) {
                return true;
            }
        }

        return false;
    }

    public function scopeForOrganization($query, ?string $orgHex)
    {
        if (!$orgHex) return $query;
        try {
            $bin = hex2bin($orgHex);
        } catch (\Throwable $e) {
            return $query;
        }

        return $query->where('organization_id', $bin);
    }

    public function toArray()
    {
        $data = $this->hexIdToArray();
        if (array_key_exists('organization_id', $data)) {
            $data['organization_id'] = (string)($this->formatBinaryToHex($this->attributes['organization_id'] ?? null) ?? $data['organization_id']);
        }
        if (array_key_exists('role_id', $data)) {
            $data['role_id'] = (string)($this->formatBinaryToHex($this->attributes['role_id'] ?? null) ?? $data['role_id']);
        }
        return $data;
    }
}
