<?php

namespace App\Http\Requests\Admin;

use App\Models\Product;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class ProductRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        /** @var Product|null $product */
        $product = $this->route('product');

        return [
            'category_id' => ['required', 'exists:categories,id'],
            'brand_id' => ['nullable', 'exists:brands,id'],
            'name' => ['required', 'string', 'max:255'],
            'slug' => ['nullable', 'string', 'max:255', 'alpha_dash', Rule::unique('products', 'slug')->ignore($product)],
            'sku' => ['required', 'string', 'max:100', Rule::unique('products', 'sku')->ignore($product)],
            'barcode' => ['nullable', 'string', 'max:100'],
            'short_description' => ['nullable', 'string', 'max:500'],
            'description' => ['required', 'string'],
            'spec_keys' => ['nullable', 'array'],
            'spec_keys.*' => ['nullable', 'string', 'max:100'],
            'spec_values' => ['nullable', 'array'],
            'spec_values.*' => ['nullable', 'string', 'max:255'],

            'original_price' => ['required', 'numeric', 'min:0'],
            'sale_price' => ['nullable', 'numeric', 'min:0', 'lt:original_price'],

            'status' => ['required', 'in:draft,active,inactive'],
            'is_featured' => ['boolean'],
            'is_trending' => ['boolean'],
            'is_new_arrival' => ['boolean'],
            'is_flash_sale' => ['boolean'],
            'flash_sale_starts_at' => ['nullable', 'date', 'required_if:is_flash_sale,1'],
            'flash_sale_ends_at' => ['nullable', 'date', 'after:flash_sale_starts_at', 'required_if:is_flash_sale,1'],

            'meta_title' => ['nullable', 'string', 'max:255'],
            'meta_description' => ['nullable', 'string', 'max:500'],

            'tags' => ['nullable', 'array'],
            'tags.*' => ['exists:tags,id'],

            'images' => [$product ? 'nullable' : 'required', 'array'],
            'images.*' => ['image', 'max:4096'],
            'primary_image' => ['nullable', 'integer', 'min:0'],
            'existing_primary_image' => ['nullable', 'integer', 'exists:product_images,id'],
            'remove_images' => ['nullable', 'array'],
            'remove_images.*' => ['integer', 'exists:product_images,id'],

            'has_variants' => ['boolean'],
            'stock_quantity' => ['required_if:has_variants,0', 'nullable', 'integer', 'min:0'],
            'low_stock_threshold' => ['nullable', 'integer', 'min:0'],

            'variants' => ['required_if:has_variants,1', 'nullable', 'array'],
            'variants.*.color_id' => ['nullable', 'exists:colors,id'],
            'variants.*.size_id' => ['nullable', 'exists:sizes,id'],
            'variants.*.quantity' => ['required', 'integer', 'min:0'],
            'variants.*.price_override' => ['nullable', 'numeric', 'min:0'],
        ];
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'is_featured' => $this->boolean('is_featured'),
            'is_trending' => $this->boolean('is_trending'),
            'is_new_arrival' => $this->boolean('is_new_arrival'),
            'is_flash_sale' => $this->boolean('is_flash_sale'),
            'has_variants' => $this->boolean('has_variants'),
        ]);
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            /** @var Product|null $product */
            $product = $this->route('product');

            $removeIds = $this->input('remove_images', []);

            // Only relevant when this request is actually removing images —
            // a product that already has zero (e.g. never had one added)
            // isn't this request's problem to relitigate on every unrelated
            // edit (changing price, variants, etc).
            if (! $product || empty($removeIds)) {
                return;
            }

            $remaining = $product->images()->count() - count($removeIds) + count($this->file('images', []));

            if ($remaining < 1) {
                $validator->errors()->add('remove_images', 'A product must have at least one image — upload a replacement before removing the last one.');
            }
        });
    }
}
