<?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
    {
        $perPage = min((int) $request->input('per_page', 15), 200);

        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')
            ->when($request->filled('search_term'), function ($query) use ($request) {
                $term = '%' . $request->input('search_term') . '%';
                $query->where(function ($q) use ($term) {
                    $q->where('vehicle_trims.name', 'LIKE', $term)
                        ->orWhere('vehicle_makes.name', 'LIKE', $term)
                        ->orWhere('vehicle_models.name', 'LIKE', $term);
                });
            })
            ->orderBy('vehicle_makes.name')
            ->orderBy('vehicle_models.name')
            ->orderBy('vehicle_trims.name')
            ->paginate($perPage));
    }

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

    public function store(Request $request, VehicleTrimRepository $repository): 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);

        if (!empty($trim->template_id)) {
            $repository->syncContentWithTemplate($trim->id);
            $trim->refresh();
        }

        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);
    }
}
