<?php

namespace App\Models;

use App\Enums\UserRole;
use App\Enums\UserStatus;
use App\Support\EmailNormalizer;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'role',
        'status',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'role' => UserRole::class,
        'status' => UserStatus::class,
    ];

    protected function email(): Attribute
    {
        return Attribute::make(
            set: fn (?string $value) => EmailNormalizer::normalize($value),
        );
    }

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

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

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

    public function managedPromoters(): BelongsToMany
    {
        return $this->belongsToMany(Promoter::class, 'promoter_user');
    }

    public function managedAuthorisedPartners(): BelongsToMany
    {
        return $this->belongsToMany(AuthorisedPartner::class, 'authorised_partner_user');
    }

    public function managedCoursewarePartners(): BelongsToMany
    {
        return $this->belongsToMany(CoursewarePartner::class, 'courseware_partner_user');
    }

    public function isSuperAdmin(): bool
    {
        return $this->role === UserRole::SuperAdmin;
    }

    public function isPromoter(): bool
    {
        return $this->role === UserRole::Promoter;
    }

    public function isAuthorisedPartner(): bool
    {
        return $this->role === UserRole::AuthorisedPartner;
    }

    public function isCoursewarePartner(): bool
    {
        return $this->role === UserRole::CoursewarePartner;
    }

    public function isApproved(): bool
    {
        return $this->status === UserStatus::Approved;
    }

    public function initials(): string
    {
        $parts = preg_split('/\s+/', trim((string) $this->name)) ?: [];
        $parts = array_values(array_filter($parts));

        if (count($parts) >= 2) {
            return strtoupper(mb_substr($parts[0], 0, 1).mb_substr($parts[1], 0, 1));
        }

        $name = $parts[0] ?? 'U';

        return strtoupper(mb_substr($name, 0, min(2, mb_strlen($name))));
    }
}
