<?php

namespace App\Models;

use App\Scopes\DailyCountBetweenDate;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Facades\Auth;

class Page extends Model
{
    use HasFactory, DailyCountBetweenDate;

    protected $fillable = [
        'user_id',
        'prompt',
        'illustration',
        'colored_count',
        'favorited_count',
        'trending',
        'blocked',
    ];

    protected function casts(): array
    {
        return [
            'trending' => 'boolean',
            'blocked' => 'boolean',
        ];
    }

    protected function isColored(): Attribute
    {
        return Attribute::make(
            get: function () {
                if (!Auth::check()) return false;
                return $this->coloreds()
                    ->whereUserId(Auth::id())
                    ->exists();
            },
        );
    }

    protected function isFavorited(): Attribute
    {
        return Attribute::make(
            get: function () {
                if (!Auth::check()) return false;
                return $this->favoritedUsers()
                    ->whereId(Auth::id())
                    ->exists();
            },
        );
    }

    protected function isOwner(): Attribute
    {
        return Attribute::make(
            get: function () {
                if (!Auth::check()) return false;
                if (Auth::user()->admin) return true;
                return $this->user_id === Auth::id();
            },
        );
    }

    public function scopeRandomOf(Builder $query, int $count = 1)
    {
        return $query->inRandomOrder()->limit($count);
    }

    public function scopeCreatedThisWeek(Builder $query)
    {
        return $query->whereBetween('created_at', [
            now()->startOfWeek(),
            now(),
        ]);
    }

    public function colored()
    {
        return $this->hasOne(Colored::class)
            ->whereUserId(Auth::id())
            ->latest();
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function coloreds()
    {
        return $this->hasMany(Colored::class);
    }

    public function favoritedUsers()
    {
        return $this->belongsToMany(User::class, 'favoriteds')
            ->withTimestamps();
    }
}
