<?php

namespace Daylight\Core\Modules\Multilingualism\Entities;

use Daylight\Core\Modules\Multilingualism\Multilingualism;
use Illuminate\Contracts\Support\Arrayable;

class LocalizedRoute implements Arrayable
{
    protected string $route;

    protected mixed $properties;

    protected bool $staticRoute = false;

    protected $defaultTranslation = null;

    protected $translations = [];

    public function setRoute(string $route, array|string|null $properties = null): self
    {
        $this->route = $route;
        $this->properties = $properties;

        return $this;
    }

    public function staticRoute(bool $static = true): self
    {
        $this->staticRoute = $static;

        return $this;
    }

    public function setDefaultTranslation($translation): self
    {
        $this->defaultTranslation = $translation;

        return $this;
    }

    public function setTranslations($translations): self
    {
        $this->translations = $translations;

        return $this;
    }

    public static function create(): self
    {
        return new self;
    }

    public function getCanonical(): string
    {
        return $this->refactorHomeUrl(
            route(app()->getLocale() . '_' . $this->route, $this->properties ?? [])
        );
    }

    public function getHrefLangLinks(bool $withDefault = true): array
    {
        if ($this->staticRoute) {
            return [
                ...$withDefault
                    ? [
                        'x-default' => $this->refactorHomeUrl(
                            route(config('multilingualism.default_locale') . '_' . $this->route, $this->properties ?? [])
                        ),
                    ]
                    : [],

                ...Multilingualism::getAvailableLocales()->mapWithKeys(function ($locale) {
                    return [$locale => $this->refactorHomeUrl(translatedRoute($this->route, $this->properties, $locale))];
                })->toArray(),
            ];
        }

        return [
            ...$withDefault
                ? [
                    'x-default' => $this->refactorHomeUrl(
                        route(config('multilingualism.default_locale') . '_' . $this->route, $this->defaultTranslation?->slug ?? [])
                    ),
                ]
                : [],
            ...$this->translations->mapWithKeys(function ($translation) {
                return [
                    $translation->locale => $this->refactorHomeUrl(route($translation->locale . '_' . $this->route, $translation->slug)),
                ];
            })->toArray(),
        ];
    }

    public function toArray(): array
    {
        return [
            'canonical' => $this->route,
        ];
    }

    private function refactorHomeUrl(string $url): string
    {
        return str_ireplace(['/home', '/homepagina', '/homepage', '/startpagina'], '/', $url);
    }
}
