<?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 $exception) {
            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 $exception) {
            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 $exception) {
            return null;
        }
    }

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

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

    public function baseUrl(): string
    {
        $domain = tenant()->domains()
            ->orderByDesc('primary')
            ->firstOrFail();

        $protocol = config('app.env') === 'local' ? 'http://' : 'https://';

        return $protocol . $domain->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);
    }
}
