<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\IronResource;
use App\Models\Iron;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

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

    public function show(Iron $iron)
    {
        return new IronResource($iron);
    }

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

        $payload = $this->filterToTableColumns('irons', $request->all());
        $iron = Iron::create($payload);

        return (new IronResource($iron))
            ->response()
            ->setStatusCode(201);
    }

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

        $payload = $this->filterToTableColumns('irons', $request->all());
        $iron->update($payload);

        return new IronResource($iron);
    }

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