<?php

namespace App\Modules\VehicleTrims\Http\Controllers;

use App\Facades\Settings;
use App\Modules\VehicleTrims\Http\Requests\UpdateTrimRequest;
use App\Modules\VehicleTrims\Http\Resources\VehicleTrimList;
use App\Modules\VehicleTrims\Http\Resources\VehicleTrimView;
use App\VehicleTrimRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\VehicleTrim;

class VehicleTrimController
{
    public function index(Request $request): VehicleTrimList
    {
        return new VehicleTrimList(VehicleTrim::query()
            ->select(['vehicle_trims.*'])
            ->leftJoin('vehicle_makes', 'vehicle_trims.make_id', 'vehicle_makes.id')
            ->leftJoin('vehicle_models', 'model_id', 'vehicle_models.id')
            ->orderBy('vehicle_makes.name')
            ->orderBy('vehicle_models.name')
            ->orderBy('vehicle_trims.name')
            ->paginate());
    }

    public function show(VehicleTrim $vehicle_trim): VehicleTrimView
    {
        return new VehicleTrimView($vehicle_trim);
    }

    public function store(Request $request): VehicleTrimView
    {
        $data = $request->input();

        if (empty($data['template_id'])) {
            $templateId = Settings::get('app-content-trim-default-template');
            if (!empty($templateId)) {
                $data['template_id'] = $templateId;
            }
        }

        $trim = VehicleTrim::query()->create($data);
        return new VehicleTrimView($trim);
    }

    public function update(
        UpdateTrimRequest $request,
        VehicleTrim $vehicle_trim,
        VehicleTrimRepository $repository
    ): VehicleTrimView {
        $repository->save($vehicle_trim, $request);
        return new VehicleTrimView($vehicle_trim->fresh());
    }

    public function destroy(Request $request, VehicleTrim $vehicle_trim): VehicleTrimList
    {
        $vehicle_trim->delete();
        return $this->index($request);
    }

    public function copy(Request $request, VehicleTrim $vehicle_trim): VehicleTrimView
    {
        $data = $vehicle_trim->toArray();
        unset($data['slug']);
        $copy = VehicleTrim::query()->create($data);

        $vehicle_trim->attributeValues->each(function ($attributeValue) use ($copy) {
            $newValue = $attributeValue->replicate();
            $newValue->owner_id = $copy->id;
            $newValue->save();
        });

        return new VehicleTrimView($copy);
    }

    public function syncWithTemplate(int $vehicleTrimId, VehicleTrimRepository $repository): VehicleTrimView|array
    {
        try {
            $repository->syncContentWithTemplate($vehicleTrimId);
            $trim = VehicleTrim::query()->find($vehicleTrimId);
        } catch (\Exception $exception) {
            Log::error('Failed to sync trim structure', [
                'trim_id' => $vehicleTrimId,
                'error' => $exception->getMessage(),
                'tenant' => tenant('id'),
            ]);

            return [
                'success' => false,
                'error' => $exception->getMessage(),
            ];
        }

        return new VehicleTrimView($trim);
    }
}
