<?php

namespace App;

use App\Models\Image;
use App\Models\Memo;
use App\Models\ToDoList;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'login_at',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    protected $dates = ['login_at'];

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

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

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

    public function images(): MorphMany
    {
        return $this->morphMany(Image::class, 'imageable');
    }

    public function profileImage(): MorphOne
    {
        return $this->morphOne(Image::class, 'imageable')
            ->where('location', 'profile')
            ->orderBy('id', 'desc')
            ->withDefault(function ($userImage) {
                $userImage->path = 'images/default-cover.jpg';
            });
    }

    public function coverImage(): MorphOne
    {
        return $this->morphOne(Image::class, 'imageable')
            ->where('location', 'cover')
            ->orderBy('id', 'desc')
            ->withDefault(function ($userImage) {
                $userImage->path = 'images/default-cover.jpg';
            });
    }

    public function thumbnailImage(): MorphOne
    {
        return $this->morphOne(Image::class, 'imageable')
            ->orderBy('id', 'desc')
            ->where('location', 'profile-small')
            ->withDefault(function ($userImage) {
                $userImage->path = 'images/default-cover.jpg';
            });
    }
}
