<?php

namespace App\Http\Requests;

use App\Models\UserOperation;
use Illuminate\Foundation\Http\FormRequest;

class UpdateUserOperationRequest extends FormRequest
{
    public function authorize(): bool
    {
        return auth()->check() && auth()->user()->role === 'admin';
    }

    public function rules(): array
    {
        return [
            // You can still validate project_id and user_id, but these are not editable in the form
            'project_id' => 'required|exists:projects,id',
            'user_id' => 'required|exists:users,id',
            'designation' => 'required|numeric|min:0',
            'tech_skills' => 'required|numeric|min:0',
            'power' => 'required|numeric|min:0',
            'influence' => 'required|numeric|min:0',
            'interpersonal_relationship' => 'required|numeric|min:0',
            'experience' => 'required|numeric|min:0',
        ];
    }

    public function attributes(): array
    {
        return [
            'project_id' => 'Project',
            'user_id' => 'Stakeholder',
            'designation' => 'Designation',
            'tech_skills' => 'Technical Skills',
            'power' => 'Power',
            'influence' => 'Influence',
            'interpersonal_relationship' => 'Interpersonal Relationship',
            'experience' => 'Experience',
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $projectId = $this->input('project_id');
            $userId = $this->input('user_id');

            if ($projectId && $userId) {
                $exists = UserOperation::where('project_id', $projectId)
                    ->where('user_id', $userId)
                    ->where('id', '!=', $this->route('userOperation')->id) // exclude current record
                    ->exists();

                if ($exists) {
                    $validator->errors()->add('user_id', 'This stakeholder is already assigned to the selected project.');
                }
            }
        });
    }
}
