<?php

namespace App\Http\Requests;

use App\Models\Invoice;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;

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

    public function rules(): array
    {
        return [
            'original_invoice_id' => ['required', 'exists:invoices,id'],
            'invoice_date' => ['required', 'date_format:Y-m-d'],
            'scenario_id' => ['nullable', 'string', 'regex:/^SN0\d{2}$/'],
            'notes' => ['nullable', 'string', 'max:2000'],

            'items' => ['required', 'array', 'min:1'],
            'items.*.item_id' => ['nullable', 'exists:items,id'],
            'items.*.hs_code' => ['required_without:items.*.item_id', 'nullable', 'string'],
            'items.*.product_description' => ['required_without:items.*.item_id', 'nullable', 'string'],
            'items.*.rate' => ['required_without:items.*.item_id', 'nullable'],
            'items.*.uom' => ['required_without:items.*.item_id', 'nullable', 'string'],
            'items.*.quantity' => ['required', 'numeric', 'min:0.0001'],
            'items.*.value_sales_excluding_st' => ['nullable', 'numeric', 'min:0'],
            'items.*.sale_type' => ['required_without:items.*.item_id', 'nullable', 'string'],

            'sync_immediately' => ['boolean'],
        ];
    }

    /**
     * Application-level guard: the referenced invoice must already be
     * Synced with FBR (you can't issue a correction against something
     * FBR has never seen) and must not itself be a note.
     */
    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $original = Invoice::find($this->input('original_invoice_id'));

            if (! $original) {
                return; // exists:invoices,id already caught this
            }

            if (! $original->isSynced()) {
                $validator->errors()->add(
                    'original_invoice_id',
                    'The original invoice must be successfully synced with FBR before a Debit/Credit Note can be filed against it.'
                );
            }

            if ($original->isNote()) {
                $validator->errors()->add(
                    'original_invoice_id',
                    'A Debit/Credit Note cannot be filed against another note.'
                );
            }
        });
    }
}
