<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

/**
 * Shape-only validation for create + update of a Stock Take.
 *
 * `store_id` + `take_date` are required on create. `name` / `notes` are
 * optional metadata. The items array isn't accepted on create — items
 * are auto-snapshotted from `product_stock_levels` inside
 * {@see \App\Actions\Inventory\CreateStockTake}. On update, items[]
 * is the sparse list of counted-quantity changes per row.
 */
class StockTakeRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    /** @return array<string, mixed> */
    public function rules(): array
    {
        $isCreate = $this->isMethod('post') && ! $this->route('stockTake');

        return [
            'store_id'  => [$isCreate ? 'required' : 'sometimes', 'integer', Rule::exists('stores', 'id')->where('is_active', true)],
            'take_date' => [$isCreate ? 'required' : 'sometimes', 'date'],
            'name'      => ['nullable', 'string', 'max:191'],
            'notes'     => ['nullable', 'string', 'max:1000'],

            // Items only sent on update. Each entry references an
            // existing item by `id`; counted_quantity can be null
            // (= skipped) or any numeric incl. zero.
            'items'                    => ['sometimes', 'array', 'max:5000'],
            'items.*.id'               => ['required', 'integer'],
            'items.*.counted_quantity' => ['nullable'],
            'items.*.notes'            => ['nullable', 'string', 'max:191'],
        ];
    }

    /** @return array<string, string> */
    public function messages(): array
    {
        return [
            'store_id.required'  => __('stock_takes.errors.store_required'),
            'take_date.required' => __('stock_takes.errors.date_required'),
        ];
    }

    /**
     * Header attributes consumed by CreateStockTake.
     *
     * @return array<string, mixed>
     */
    public function headerAttributes(): array
    {
        $data = $this->validated();
        return [
            'store_id'  => (int) $data['store_id'],
            'take_date' => $data['take_date'],
            'name'      => $data['name']  ?? null,
            'notes'     => $data['notes'] ?? null,
        ];
    }

    /**
     * Update payload consumed by UpdateStockTake.
     *
     * @return array<string, mixed>
     */
    public function updateAttributes(): array
    {
        $data = $this->validated();
        $out = [
            'name'      => $data['name']      ?? null,
            'take_date' => $data['take_date'] ?? null,
            'notes'     => $data['notes']     ?? null,
        ];
        if (!empty($data['items'] ?? [])) {
            $out['items'] = array_map(fn ($r) => [
                'id'               => (int) $r['id'],
                'counted_quantity' => $r['counted_quantity'] ?? null,
                'notes'            => $r['notes'] ?? null,
            ], $data['items']);
        }
        return $out;
    }
}
