<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\ProfileResource;
use App\Models\Profile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

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

    public function show(Profile $profile)
    {
        return new ProfileResource($profile);
    }

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

        $payload = $this->filterToTableColumns('profiles', $request->all());
        $profile = Profile::create($payload);

        return (new ProfileResource($profile))
            ->response()
            ->setStatusCode(201);
    }

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

        $payload = $this->filterToTableColumns('profiles', $request->all());
        $profile->update($payload);

        return new ProfileResource($profile);
    }

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