<?php

namespace App\Models;

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

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

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'company_id',
        'role_id',
        'name',
        'username',
        'email',
        'phone',
        'password',
        'status',
        'notification_preferences',
    ];

    /**
     * NT-01: push types a recipient can mute — job-critical types (a new
     * job, a cancellation, a fare change, being bumped off a job) are
     * deliberately not in this list and always send, so opting out of
     * everything isn't possible.
     */
    public const OPTIONAL_NOTIFICATIONS = [
        'document_status_changed' => 'Your document was approved or rejected',
        'document_expiring' => 'One of your documents is expiring soon',
        'vehicle_document_status_changed' => 'A vehicle document was approved or rejected',
        'vehicle_document_expiring' => 'A vehicle document is expiring soon',
        'company_subscription' => 'Company subscription/billing notices',
    ];

    /**
     * True for any type not in OPTIONAL_NOTIFICATIONS (always wanted), or
     * an optional type the user hasn't explicitly muted.
     */
    public function wantsNotification(?string $type): bool
    {
        if (! $type || ! array_key_exists($type, self::OPTIONAL_NOTIFICATIONS)) {
            return true;
        }

        return ! in_array($type, $this->notification_preferences['muted'] ?? [], true);
    }

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    public function role(): BelongsTo
    {
        return $this->belongsTo(Role::class);
    }

    public function driver(): HasOne
    {
        return $this->hasOne(Driver::class);
    }

    public function deviceTokens(): MorphMany
    {
        return $this->morphMany(DeviceToken::class, 'owner');
    }

    /**
     * A user with no company_id is a platform-wide Super Admin — the same
     * signal already used throughout the admin controllers to decide
     * whether a company picker needs to be shown on a form.
     */
    public function isSuperAdmin(): bool
    {
        return is_null($this->company_id);
    }

    public function hasPermission(string $permission): bool
    {
        if ($this->isSuperAdmin()) {
            return true;
        }

        return $this->role?->hasPermission($permission) ?? false;
    }

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

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'last_login_at' => 'datetime',
            'last_seen_changelog_at' => 'datetime',
            'notification_preferences' => 'array',
        ];
    }
}
