<?php

namespace App\Http\Requests;

use App\Models\Customer;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreCustomerRequest extends FormRequest
{
    public function authorize(): bool
    {
        return in_array($this->user()?->role, ['business_owner', 'staff'], true);
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:150'],
            'phone' => ['nullable', 'string', 'max:60'],
            'email' => ['nullable', 'email', 'max:190'],
            'status' => ['required', Rule::in(array_keys(Customer::STATUSES))],
            'birthday' => ['nullable', 'date'],
            'source' => ['nullable', 'string', 'max:100'],
            'address' => ['nullable', 'string', 'max:1000'],
            'notes' => ['nullable', 'string', 'max:3000'],
        ];
    }

    public function validatedPayload(): array
    {
        $validated = $this->validated();
        $meta = [
            'address' => $validated['address'] ?? null,
            'notes_history' => [],
        ];

        if (! empty($validated['notes'])) {
            $meta['notes_history'][] = [
                'author' => $this->user()?->name ?? 'Team member',
                'date' => now()->toDateString(),
                'text' => $validated['notes'],
            ];
        }

        return [
            'name' => $validated['name'],
            'phone' => $validated['phone'] ?? null,
            'email' => $validated['email'] ?? null,
            'status' => $validated['status'],
            'birthday' => $validated['birthday'] ?? null,
            'source' => $validated['source'] ?? null,
            'notes' => $validated['notes'] ?? null,
            'meta' => $meta,
        ];
    }
}
