<?php

namespace App\Http\Controllers;

use App\Http\Resources\ShortcodeList;
use App\Http\Resources\ShortcodeView;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\Shortcode;

class ShortcodeController extends Controller
{
    public function __construct()
    {
        $this->middleware([
            'permission:edit-content',
        ]);
    }

    public function index(Request $request)
    {
        $perPage = min((int) $request->input('per_page', 15), 200);

        $codes = Shortcode::query()
            ->setSortBy($request->input('sort_by', 'id_desc'))
            ->when(
                $request->filled('search_term'),
                function ($query) use ($request) {
                    $query->where('name', 'like', '%' . $request->input('search_term') . '%')
                        ->orWhere('code', 'like', '%' . $request->input('search_term') . '%');
                }
            )
            ->paginate($perPage);

        return new ShortcodeList($codes);
    }

    public function store(Request $request): ShortcodeView
    {
        return new ShortcodeView(Shortcode::query()->create([
            'name' => $request->input('name'),
            'code' => strtoupper(Str::snake($request->input('name'))),
            'model' => 'vehicle',
        ]));
    }

    public function show(Shortcode $shortcode): ShortcodeView
    {
        return new ShortcodeView($shortcode);
    }


    public function update(Request $request, Shortcode $shortcode): ShortcodeView
    {
        $shortcode->update($request->input());

        $conditions = collect($request->input('conditions', []));

        // Remove rules not in list
        $shortcode->conditions()
            ->whereNotIn('id', $conditions->pluck('id'))
            ->delete();

        // Add/Update rules
        $conditions->each(fn($condition) => $shortcode->conditions()
            ->updateOrCreate(['id' => $condition['id'] ?? null], $condition));

        return new ShortcodeView($shortcode);
    }

    public function destroy(Shortcode $shortcode)
    {
        return $shortcode->delete();
    }
}
