<?php

namespace Daylight\Core\Http\Controllers\Store\API;

use Daylight\Core\Http\Controllers\Controller;
use Daylight\Core\Http\Requests\Store\API\SearchVariantRequest;
use Daylight\Core\Models\Variant;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class VariantSearchController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:read:products'),
        ];
    }

    public function __invoke(SearchVariantRequest $request): array
    {
        $variants = daylightModel('variant')::query()
            ->where('sku', 'like', '%' . $request->get('searchQuery') . '%')
            ->wherePurchasable(1)
            ->whereNull('product_id')
            ->with('media')
            ->limit(10)
            ->get();

        $exactVariant = daylightModel('variant')::query()
            ->where('sku', $request->get('searchQuery'))
            ->wherePurchasable(1)
            ->whereNull('product_id')
            ->with('media')
            ->first();

        return [
            'exactMatch' => $exactVariant
                ? [
                    'id' => $exactVariant->id,
                    'sku' => $exactVariant->sku,
                    'name' => $exactVariant->name,
                    'image' => $exactVariant->media->first()?->getUrl('thumbnail'),
                ]
                : null,
            'variants' => $variants->map(function (Variant $variant) {
                return [
                    'id' => $variant->id,
                    'sku' => $variant->sku,
                    'name' => $variant->name,
                    'image' => $variant->media->first()?->getUrl('thumbnail'),
                ];
            }),
        ];
    }
}
