<?php

namespace App\Http\Requests;

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

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

    public function rules(): array
    {
        $businessId = $this->attributes->get('current_business')?->id;

        return [
            'name' => ['required', 'string', 'max:150'],
            'role' => ['nullable', 'string', 'max:120'],
            'email' => ['nullable', 'email', 'max:190'],
            'phone' => ['nullable', 'string', 'max:60'],
            'availability_status' => ['required', Rule::in(array_keys(StaffProfile::AVAILABILITY_STATUSES))],
            'calendar_color' => ['nullable', 'string', 'max:20'],
            'bio' => ['nullable', 'string', 'max:3000'],
            'avatar' => ['nullable', 'image', 'max:2048'],
            'service_ids' => ['nullable', 'array'],
            'service_ids.*' => [
                'integer',
                Rule::exists('services', 'id')->where('business_id', $businessId),
            ],
        ];
    }

    public function validatedPayload(): array
    {
        $validated = $this->validated();
        $availability = $validated['availability_status'];

        return [
            'name' => $validated['name'],
            'role' => $validated['role'] ?? null,
            'email' => $validated['email'] ?? null,
            'phone' => $validated['phone'] ?? null,
            'bio' => $validated['bio'] ?? null,
            'color' => $validated['calendar_color'] ?? '#2563EB',
            'status' => $availability === StaffProfile::STATUS_INACTIVE ? StaffProfile::STATUS_INACTIVE : StaffProfile::STATUS_ACTIVE,
            'availability_status' => $availability === StaffProfile::STATUS_INACTIVE ? StaffProfile::AVAILABILITY_OFF_TODAY : $availability,
        ];
    }
}
