<?php

namespace App\Modules\ServiceBooking\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\ServiceBooking\Http\Requests\CreateBookingPackageRequest;
use App\Modules\ServiceBooking\Http\Requests\UpdateBookingPackageRequest;
use App\Modules\ServiceBooking\Http\Resources\ListServicePackages;
use App\Modules\ServiceBooking\Http\Resources\ViewServicePackage;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\ServicePackage;

class ServicePackageController extends Controller
{
    public function index(Request $request): ListServicePackages
    {
        $bookings = ServicePackage::query()
            ->setSortBy($request->input('order_by'))
            ->paginate();
        return new ListServicePackages($bookings);
    }

    public function store(CreateBookingPackageRequest $request): ViewServicePackage
    {
        $package = ServicePackage::query()->create($request->validated());
        return new ViewServicePackage($package);
    }

    public function show(ServicePackage $package): ViewServicePackage
    {
        return new ViewServicePackage($package);
    }

    public function update(UpdateBookingPackageRequest $request, ServicePackage $package): ViewServicePackage
    {
        $package->update($request->validated());
        return new ViewServicePackage($package);
    }

    public function destroy(ServicePackage $package): Response
    {
        $package->delete();
        return \response('ok');
    }

    public function saveOrder(Request $request): Response|JsonResponse
    {
        $ids = collect($request->input())->pluck('id');

        $originalOrders = ServicePackage::query()
            ->whereIn('id', $ids)
            ->orderBy('order')
            ->get(['id', 'order'])
            ->pluck('order', 'id');
        try {
            DB::transaction(static function () use ($ids, $originalOrders) {
                $ids
                    ->filter(fn ($id, $newOrderValue) => $originalOrders[$id] !== $newOrderValue)
                    ->each(function ($id, $newOrderValue) {
                        ServicePackage::query()
                            ->where('id', $id)
                            ->update([
                                'order' => $newOrderValue,
                            ]);
                    });
            });

            return response('ok');
        } catch (\Throwable $e) {
            Log::error('Failed to save vehicle offer order', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'tenant' => tenant('id'),
            ]);

            return response()->json([
                'status' => 'error',
                'message' => 'Failed to save the new order. Please try again.',
            ], 500);
        }
    }
}
