<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Http\Resources\DealershipList;
use App\Http\Resources\DealershipView;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Services\LocatingService;

class DealershipController extends Controller
{
    public function index(Request $request, LocatingService $service)
    {
        return new DealershipList(Dealership::query()
            ->where('active', 1)
            ->with([
                'mediaUses.media',
                'franchise',
                'departments',
                'primaryDepartment',
            ])
            ->when(
                Settings::get('dealerships-sort-order', 'name') === 'order',
                fn($query) => $query->orderBy('order'),
                fn($query) => $query->orderBy('name')
            )
            ->nearPostcode($request->input('postcode'))
            ->get());
    }

    public function show(string $dealership_slug)
    {
        $dealership = Dealership::query()->where('slug', $dealership_slug)->firstOrFail();
        if (!$dealership->active) {
            return response('Not Found', 404);
        }
        return new DealershipView($dealership);
    }
}
