<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\AccessoryResource;
use App\Models\Accessory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

class AccessoryController extends Controller
{
    public function index(Request $request)
    {
        $perPage = (int) $request->get('per_page', 50);
        return AccessoryResource::collection(Accessory::query()->latest()->paginate($perPage));
    }

    public function show(Accessory $accessory)
    {
        return new AccessoryResource($accessory);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'unit' => ['nullable', 'string', 'max:40'],
            'price' => ['nullable', 'numeric'],
        ]);

        $payload = $this->filterToTableColumns('accessories', $request->all());
        $accessory = Accessory::create($payload);

        return (new AccessoryResource($accessory))
            ->response()
            ->setStatusCode(201);
    }

    public function update(Request $request, Accessory $accessory)
    {
        $request->validate([
            'name' => ['sometimes', 'required', 'string', 'max:255'],
            'unit' => ['nullable', 'string', 'max:40'],
            'price' => ['nullable', 'numeric'],
        ]);

        $payload = $this->filterToTableColumns('accessories', $request->all());
        $accessory->update($payload);

        return new AccessoryResource($accessory);
    }

    public function destroy(Accessory $accessory)
    {
        $accessory->delete();
        return response()->json(['message' => 'Accessory deleted']);
    }

    private function filterToTableColumns(string $table, array $data): array
    {
        if (!Schema::hasTable($table)) return $data;

        $columns = Schema::getColumnListing($table);
        $blocked = ['id', 'created_at', 'updated_at', 'deleted_at'];
        $columns = array_values(array_diff($columns, $blocked));

        return array_intersect_key($data, array_flip($columns));
    }
}
