<?php

namespace App\Models;

// 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;
use Spatie\Permission\Traits\HasRoles;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'id',
        'name',
        'email',
        'password',
        'email_verified_at',
        'created_at',
        'updated_at',
    ];

    /**
     * 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',
        ];
    }

    /**
     * Get the topics created by this user.
     */
    public function topics(): HasMany
    {
        return $this->hasMany(Topic::class);
    }

    /**
     * Get the topic comments made by this user.
     */
    public function topicComments(): HasMany
    {
        return $this->hasMany(TopicComment::class);
    }

    /**
     * Get the topics this user is following.
     */
    public function followingTopics(): BelongsToMany
    {
        return $this->belongsToMany(Topic::class, 'topic_follows', 'user_id', 'topic_id')
            ->withTimestamps();
    }

    /**
     * Get the follow records for this user.
     */
    public function topicFollows(): HasMany
    {
        return $this->hasMany(TopicFollow::class);
    }

    /**
     * Get the user detail information.
     */
    public function userDetail(): HasOne
    {
        return $this->hasOne(UserDetail::class);
    }

    /**
     * Get or create user detail record
     */
    public function getOrCreateUserDetail(): UserDetail
    {
        return $this->userDetail ?: $this->userDetail()->create([]);
    }
}
