<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\VineyardRow;
use Illuminate\Http\Request;

class VineyardRowController extends Controller
{
    public function index(Request $request)
    {
        $rows = VineyardRow::with('varietyVariation.grapeVariety')
            ->when($request->filled('status'), fn ($query) => $query->where('status', $request->string('status')))
            ->when($request->filled('variety_variation_id'), fn ($query) => $query->where('variety_variation_id', $request->integer('variety_variation_id')))
            ->when($request->filled('search'), function ($query) use ($request) {
                $term = $request->string('search');
                $query->where(function ($inner) use ($term) {
                    $inner->where('location', 'like', '%' . $term . '%')
                        ->orWhereHas('varietyVariation.grapeVariety', function ($sub) use ($term) {
                            $sub->where('variety_name', 'like', '%' . $term . '%');
                        });
                });
            })
            ->orderBy('id')
            ->limit(100)
            ->get()
            ->map(function (VineyardRow $row) {
                $variation = $row->varietyVariation;
                $grape = $variation?->grapeVariety;

                return [
                    'id' => $row->getKey(),
                    'location' => $row->location,
                    'vine_count' => $row->vine_count,
                    'status' => $row->status,
                    'variety' => $variation ? [
                        'id' => $variation->getKey(),
                        'label' => $grape ? sprintf('%s — %s', $grape->variety_name, ucfirst($variation->color)) : ucfirst($variation->color),
                    ] : null,
                ];
            });

        return response()->json(['data' => $rows]);
    }
}
