<?php

namespace App\Models;

use App\Enums\DietType;
use App\Enums\MealPostType;
use App\Enums\MealPostVisibility;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\SoftDeletes;

class MealPosts extends Model
{
    use HasFactory, HasUlids, SoftDeletes;

    protected $fillable = [
        'user_id',
        'image_url',
        'caption',
        'calories',
        'proteins',
        'carbs',
        'fats',
        'title',
        'eaten_at',
        'visibility',
        'type',
        'ai_generated',
        'diet_type',
        'hidden_at',
        'hidden_by',
        'hidden_reason',
    ];

    protected $attributes = [
        'visibility' => MealPostVisibility::Private->value,
        'ai_generated' => false,
        'diet_type' => DietType::OMNIVORE->value,
    ];

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

    public function ingredients(): HasMany
    {
        return $this->hasMany(MealPostIngredients::class)->orderBy('position');
    }

    public function reviews(): HasMany
    {
        return $this->hasMany(PostReviews::class, 'meal_post_id');
    }

    public function likedByUsers(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'meal_post_likes', 'meal_posts_id', 'user_id')
            ->withTimestamps();
    }

    public function reports(): MorphMany
    {
        return $this->morphMany(Report::class, 'reportable');
    }

    public function moderationCase(): MorphOne
    {
        return $this->morphOne(ModerationCase::class, 'caseable');
    }

    public function hiddenBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'hidden_by');
    }

    public function isHidden(): bool
    {
        return $this->hidden_at !== null;
    }

    protected function casts(): array
    {
        return [
            'eaten_at' => 'datetime',
            'visibility' => MealPostVisibility::class,
            'type' => MealPostType::class,
            'diet_type' => DietType::class,
            'ai_generated' => 'boolean',
            'hidden_at' => 'datetime',
        ];
    }
}
