<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\GlassTypeResource;
use App\Models\GlassType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

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

    public function show(GlassType $glassType)
    {
        return new GlassTypeResource($glassType);
    }

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

        $payload = $this->filterToTableColumns('glass_types', $request->all());
        $glassType = GlassType::create($payload);

        return (new GlassTypeResource($glassType))
            ->response()
            ->setStatusCode(201);
    }

    public function update(Request $request, GlassType $glassType)
    {
        $request->validate([
            'name' => ['sometimes', 'required', 'string', 'max:255'],
            'price_per_m2' => ['nullable', 'numeric'],
        ]);

        $payload = $this->filterToTableColumns('glass_types', $request->all());
        $glassType->update($payload);

        return new GlassTypeResource($glassType);
    }

    public function destroy(GlassType $glassType)
    {
        $glassType->delete();
        return response()->json(['message' => 'Glass type 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));
    }
}
