<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use App\Models\EmotionTag;
use App\Models\MistakeTag;

class StoreTradeRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    protected function prepareForValidation(): void
    {
        EmotionTag::seedDefaults();
        MistakeTag::ensureDefaults();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'symbol' => ['required', 'string', 'max:30'],
            'type' => ['required', 'in:buy,sell'],
            'status' => ['required', 'in:open,closed,cancelled'],
            'entry_price' => ['required', 'numeric', 'min:0'],
            'exit_price' => ['nullable', 'numeric', 'min:0'],
            'quantity' => ['required', 'numeric', 'min:0.00000001'],
            'stop_loss' => ['nullable', 'numeric', 'min:0'],
            'take_profit' => ['nullable', 'numeric', 'min:0'],
            'profit_loss' => ['nullable', 'numeric'],
            'opened_at' => ['nullable', 'date'],
            'closed_at' => ['nullable', 'date', 'after_or_equal:opened_at'],
            'notes' => ['nullable', 'string', 'max:5000'],
            'emotion' => ['nullable', Rule::exists('emotion_tags', 'name')->where('is_active', true)],
            'trading_session' => ['nullable', 'in:Sydney,Tokyo,London,New York,Overlap,Other'],
            'followed_risk_reward' => ['nullable', 'boolean'],
            'avoided_overtrading' => ['nullable', 'boolean'],
            'psychology_note' => ['nullable', 'string', 'max:5000'],
            'mistake_tags' => ['nullable', 'array'],
            'mistake_tags.*' => ['integer', Rule::exists('mistake_tags', 'id')->where(function ($query): void {
                $query
                    ->where('is_active', true)
                    ->where(function ($query): void {
                        $query->whereNull('user_id')->orWhere('user_id', $this->user()->id);
                    });
            })],
            'screenshot' => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
        ];
    }
}
