<?php

namespace Mtc\MercuryDemoData;

use App\Jobs\ImportImagesFromUrlList;
use Illuminate\Database\Seeder;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Facades\File;
use Mtc\ContentManager\Models\Template;
use Mtc\Crm\Models\Form;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\OfferType;
use Mtc\MercuryDataModels\VehicleMake;
use Mtc\MercuryDataModels\VehicleModel;
use Mtc\MercuryDataModels\VehicleOffer;

class DemoOfferSeeder extends Seeder
{
    use DispatchesJobs;

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->dealership = Dealership::query()->first();
        $this->type = OfferType::query()->where('slug', 'new')->first();
        $this->template = Template::query()->where('slug', 'new-vehicle-offer')->first();

        collect(json_decode(File::get(dirname(__DIR__) . '/data/demo-offers.json'), true))
            ->each(fn($vehicle) => $this->import($vehicle));
    }

    /**
     * Import a single vehicle
     *
     * @param $offer_data
     * @return void
     */
    private function import($offer_data)
    {
        $images = collect($offer_data['images'] ?? [])
            ->map(fn($image) => dirname(__DIR__) . '/data/offer-images/' . $image);
        unset($offer_data['images']);

        $offer_data['form_id'] = Form::query()->where('name', 'Offer Enquiry')->first()?->id;
        $offer_data['type_id'] = $this->type?->id;
        $offer_data['dealership_id'] = $this->dealership?->id;
        $offer_data['template_id'] = $this->template?->id;
        $offer_data['make_id'] = VehicleMake::query()->updateOrCreate([
            'name' => $offer_data['make_id']
        ])->id;
        $offer_data['model_id'] = VehicleModel::query()->updateOrCreate([
            'name' => $offer_data['model_id'],
            'make_id' => $offer_data['make_id'],
        ])->id;

        /** @var VehicleOffer $offer */
        $offer = VehicleOffer::query()->create($offer_data);

        $this->dispatch(new ImportImagesFromUrlList($images, $offer));
    }
}
