<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        $rules = [
            'schedule_id'              => ['sometimes', 'integer', 'exists:schedules,id'],
            'client_id'                => ['sometimes', 'integer', 'exists:clients,id'],
            'provider_id'              => ['nullable', 'integer', 'exists:providers,id'],
            'client_payment_method_id' => ['nullable', 'integer', 'exists:client_payment_methods,id'],

            'gateway_provider'            => ['sometimes', 'string', 'max:255'],
            'gateway_entity_reference'    => ['nullable', 'string', 'max:255'],
            'gateway_entity_label'        => ['nullable', 'string', 'max:255'],
            'gateway_operation_reference' => ['nullable', 'string', 'max:255'],
            'gateway_operation_label'     => ['nullable', 'string', 'max:255'],

            'payment_method' => ['sometimes', 'in:credit_card,pix'],
            'status'         => ['sometimes', 'in:pending,processing,authorized,paid,failed,cancelled'],

            'gross_amount'        => ['sometimes', 'numeric', 'min:0'],
            'gateway_fee_amount'  => ['sometimes', 'numeric', 'min:0'],
            'platform_fee_amount' => ['sometimes', 'numeric', 'min:0'],
            'net_amount'          => ['sometimes', 'numeric', 'min:0'],
            'currency'            => ['sometimes', 'string', 'size:3'],
            'installments'        => ['sometimes', 'integer', 'min:1', 'max:24'],

            'authorized_at' => ['nullable', 'date'],
            'paid_at'       => ['nullable', 'date'],
            'failed_at'     => ['nullable', 'date'],
            'cancelled_at'  => ['nullable', 'date'],
            'expires_at'    => ['nullable', 'date'],

            'failure_code'    => ['nullable', 'string', 'max:255'],
            'failure_message' => ['nullable', 'string'],
            'gateway_payload' => ['nullable', 'array'],
            'metadata'        => ['nullable', 'array'],
        ];

        if ($this->isMethod('POST')) {
            $rules['schedule_id']    = ['required', 'integer', 'exists:schedules,id'];
            $rules['client_id']      = ['required', 'integer', 'exists:clients,id'];
            $rules['payment_method'] = ['required', 'in:credit_card,pix'];
            $rules['gross_amount']   = ['required', 'numeric', 'min:0'];
            $rules['net_amount']     = ['required', 'numeric', 'min:0'];
        }

        return $rules;
    }
}
