<?php

namespace App\Models;

use App\Notifications\ResetPasswordNotification;
use App\Services\Auth\EmailVerificationService;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    // ── Fillable ───────────────────────────────────────────────
    protected $fillable = [
        'name',
        'nickname',
        'email',
        'password',
        'role',
        'profession',
        'experience_level',
        'sector',
        'bio',
        'avatar',
        'language',
        'theme',
        'show_real_name',
        'notify_jobs',
        'notify_freelance',
        'notify_forum',
        'notify_surveys',
        'notify_documents',
        'is_active',
        'phone',
        'highly_rated_solutions_count',  // Case Practitioner badge track
        'highly_rated_replies_count',    // Field Advisor badge track
    ];

    // ── Hidden ────────────────────────────────────────────────
    protected $hidden = [
        'password',
        'remember_token',
        'phone',        // hidden by default — only shared after consent
        'email',        // hidden by default — only shared after consent
    ];

    // ── Casts ─────────────────────────────────────────────────
    protected $casts = [
        'email_verified_at'             => 'datetime',
        'password'                      => 'hashed',
        'theme'                         => 'string',
        'show_real_name'                => 'boolean',
        'notify_jobs'                   => 'boolean',
        'notify_freelance'              => 'boolean',
        'notify_forum'                  => 'boolean',
        'notify_surveys'                => 'boolean',
        'notify_documents'              => 'boolean',
        'is_active'                     => 'boolean',
        'highly_rated_solutions_count'  => 'integer',
        'highly_rated_replies_count'    => 'integer',
    ];

    // ── Helpers ───────────────────────────────────────────────

    public function getPublicNameAttribute(): string
    {
        return $this->show_real_name ? $this->name : $this->nickname;
    }

    public function isAdmin(): bool
    {
        return $this->role === 'admin';
    }

    public function isMember(): bool
    {
        return $this->role === 'member';
    }

    /**
     * When AUTH_EMAIL_VERIFICATION_ENABLED=false, treat every user as verified.
     */
    public function hasVerifiedEmail(): bool
    {
        if (! config('auth_verification.enabled')) {
            return true;
        }

        return $this->email_verified_at !== null;
    }

    public function sendEmailVerificationNotification(): void
    {
        app(EmailVerificationService::class)->issueAndSend($this);
    }

    public function sendPasswordResetNotification(#[\SensitiveParameter] $token): void
    {
        $this->notify(new ResetPasswordNotification($token));
    }

    // ── Relationships ─────────────────────────────────────────

    public function emailVerificationCodes(): HasMany
    {
        return $this->hasMany(EmailVerificationCode::class);
    }

    // ── Relationships (domain) ────────────────────────────────

    public function hubs(): BelongsToMany
    {
        return $this->belongsToMany(Hub::class, 'user_hubs')
                    ->withPivot('is_primary', 'joined_at');
    }

    public function primaryHub(): HasOne
    {
        return $this->hasOne(UserHub::class)->where('is_primary', true);
    }

    public function forumPosts(): HasMany
    {
        return $this->hasMany(ForumPost::class);
    }

    public function forumReplies(): HasMany
    {
        return $this->hasMany(ForumReply::class);
    }

    public function documents(): HasMany
    {
        return $this->hasMany(Document::class);
    }

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

    public function jobListings(): HasMany
    {
        return $this->hasMany(JobListing::class, 'posted_by');
    }

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

    public function freelanceBriefs(): HasMany
    {
        return $this->hasMany(FreelanceBrief::class);
    }

    public function surveys(): HasMany
    {
        return $this->hasMany(Survey::class, 'created_by');
    }

    public function caseProgress(): HasMany
    {
        return $this->hasMany(CaseProgress::class);
    }
}
