<?php

namespace App\Models;

use App\Enums\ModerationCaseStatus;
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\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class ModerationCase extends Model
{
    /** @use HasFactory<\Database\Factories\ModerationCaseFactory> */
    use HasFactory, HasUlids;

    protected $fillable = [
        'caseable_type',
        'caseable_id',
        'status',
        'reports_count',
        'threshold',
        'threshold_notified_at',
        'assigned_to',
        'resolved_by',
        'resolved_at',
        'resolution_note',
    ];

    public function caseable(): MorphTo
    {
        return $this->morphTo();
    }

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

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

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

    public function targetType(): string
    {
        return match ($this->caseable_type) {
            MealPosts::class => 'meal_post',
            PostReviews::class => 'post_review',
            User::class => 'user',
            default => 'unknown',
        };
    }

    public function targetLabel(): string
    {
        return match ($this->caseable_type) {
            MealPosts::class => __('admin.moderation_cases.targets.meal_post'),
            PostReviews::class => __('admin.moderation_cases.targets.post_review'),
            User::class => __('admin.moderation_cases.targets.user'),
            default => __('admin.moderation_cases.targets.unknown'),
        };
    }

    public function targetTitle(): string
    {
        $target = $this->caseable;

        return match (true) {
            $target instanceof MealPosts => $target->title,
            $target instanceof PostReviews => filled($target->comment)
                ? str($target->comment)->limit(80)->toString()
                : __('admin.moderation_cases.targets.post_review'),
            $target instanceof User => $target->name,
            default => (string) $this->caseable_id,
        };
    }

    protected function casts(): array
    {
        return [
            'status' => ModerationCaseStatus::class,
            'reports_count' => 'integer',
            'threshold' => 'integer',
            'threshold_notified_at' => 'datetime',
            'resolved_at' => 'datetime',
        ];
    }
}
