<?php

declare(strict_types=1);

namespace App\Support;

use App\Models\MediaItem;
use App\Models\Page;
use App\Models\Post;
use App\Models\Product;
use App\Models\Project;
use App\Models\Service;
use InvalidArgumentException;

class MorphTypeResolver
{
  private const ALIASES = [
    'page' => Page::class,
    'post' => Post::class,
    'product' => Product::class,
    'project' => Project::class,
    'service' => Service::class,
    'media_item' => MediaItem::class,
    'mediaitem' => MediaItem::class,
  ];

  public static function resolve(string|\Stringable $type): string
  {
    $type = trim((string) $type);

    if ($type === '') {
      throw new InvalidArgumentException('نوع مدل الزامی است.');
    }

    if (class_exists($type) && is_subclass_of($type, \Illuminate\Database\Eloquent\Model::class)) {
      return $type;
    }

    $key = strtolower($type);

    if (isset(self::ALIASES[$key])) {
      return self::ALIASES[$key];
    }

    $candidate = 'App\\Models\\' . str($type)->studly();

    if (class_exists($candidate) && is_subclass_of($candidate, \Illuminate\Database\Eloquent\Model::class)) {
      return $candidate;
    }

    throw new InvalidArgumentException('نوع مدل معتبر نیست.');
  }
}
