<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Http\Resources\FranchiseResource;
use App\Http\Resources\OfferListResource;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\Franchise;
use Mtc\MercuryDataModels\VehicleModel;
use Mtc\MercuryDataModels\VehicleOffer;

class FranchiseController extends Controller
{
    public function show(Franchise $franchise): FranchiseResource
    {
        return new FranchiseResource($franchise);
    }

    public function offers(Request $request, Franchise $franchise): array
    {
        $featured = VehicleOffer::query()
            ->active()
            ->withListingRelationships()
            ->when($request->filled('offer_type'), fn ($query) => $query
                ->whereHas('offerType', fn ($typeQuery) => $typeQuery->where('slug', $request->input('offer_type'))))
            ->where('make_id', $franchise->make_id)
            ->where('featured', 1)
            ->get();

        $models = VehicleModel::query()
            ->where('make_id', $franchise->make_id)
            ->whereHas('cheapestActiveOffer')
            ->when($request->filled('offer_type'), fn ($query) => $query
                ->whereHas(
                    'cheapestActiveOffer.offerType',
                    fn ($typeQuery) => $typeQuery->where('slug', $request->input('offer_type'))
                ))
            ->with([
                'cheapestActiveOffer.primaryMediaUse.media',
                'cheapestActiveOffer.make',
                'cheapestActiveOffer.model',
                'cheapestActiveOffer.offerType',
                'cheapestActiveOffer.bodyStyle',
                'make',
                'cheapestActiveOffer.franchise',
                'cheapestActiveOffer.make',
                'cheapestActiveOffer.model',
                'cheapestActiveOffer.fuelType',
                'cheapestActiveOffer.transmission',
                'cheapestActiveOffer.drivetrain',
                'cheapestActiveOffer.bodyStyle',
            ])
            ->when(
                Settings::get('offer-list-load-features'),
                fn ($query) => $query->with('cheapestActiveOffer.features')
            )
            ->get()
            ->groupBy(fn ($model) => $model->slug)
            ->map(fn ($group) => new OfferListResource($group->map(fn ($model) => $model->cheapestActiveOffer)));

        return [
            'featured' => new OfferListResource($featured),
            'models' => $models
        ];
    }
}
