<?php

namespace App;

use App\Facades\Settings;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\NewCar;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleOffer;

class SiteRepository
{
    public function vehicleUrl(Vehicle $vehicle, bool $withAccess = false): ?string
    {
        try {
            $access =  '?' . http_build_query([
                    'a' => base64_encode($vehicle->id . '-' . $vehicle->slug),
                ]);
            return $this->baseUrl() . $this->getVehiclePath($vehicle) . ($withAccess ? $access : '');
        } catch (ModelNotFoundException) {
            return null;
        }
    }

    public function offerUrl(VehicleOffer $offer, bool $withAccess = false): ?string
    {
        try {
            $access = '?' . http_build_query([
                    'a' => base64_encode($offer->id . '-' . $offer->slug),
                ]);
            return $this->baseUrl() . '/offer/' . $offer->slug . ($withAccess ? $access : '');
        } catch (ModelNotFoundException) {
            return null;
        }
    }

    public function newCarUrl(NewCar $newCar, bool $withAccess = false): ?string
    {
        try {
            $access = '?' . http_build_query([
                    'a' => base64_encode($newCar->id . '-' . $newCar->slug),
                ]);
            return $this->baseUrl() . '/new/' . $newCar->slug . ($withAccess ? $access : '');
        } catch (ModelNotFoundException) {
            return null;
        }
    }

    public function dealershipUrl(Dealership $dealership): ?string
    {
        try {
            return Settings::get('dealerships-url-path') . $dealership->slug;
        } catch (ModelNotFoundException) {
            return null;
        }
    }

    public function vehicleComparisonUrl(array $slugs = []): string
    {
        $path = empty(Settings::get('vehicles-compare-path'))
            ? 'compare'
            : Settings::get('vehicles-compare-path');

        $params = empty($slugs)
            ? ''
            : '?slug=' . implode('&slug=', $slugs);

        return $this->baseUrl() . '/' . ltrim((string) $path, '/') . $params;
    }

    public function url(string $endpoint = ''): ?string
    {
        try {
            return $this->baseUrl() . '/' . ltrim($endpoint, '/');
        } catch (ModelNotFoundException) {
            return null;
        }
    }

    public function baseUrl(): string
    {
        $protocol = config('app.env') === 'local' ? 'http://' : 'https://';
        return $protocol . $this->siteDomain();
    }

    public function siteDomain(): string
    {
        return tenant()->domains()
            ->orderByDesc('primary')
            ->firstOrFail()
            ->domain;
    }

    private function getVehiclePath(Vehicle $vehicle): string
    {
        $path = Settings::get('vehicles-url-path');
        $replacements = [
            '{{MAKE}}' => $vehicle->make?->slug ?? 'make',
            '{{MODEL}}' => $vehicle->model?->slug ?? 'model',
            '{{SLUG}}' => $vehicle->slug,
        ];
        return str_replace(array_keys($replacements), $replacements, $path);
    }
}
