<?php

namespace App\Http\Requests;

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

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

    public function rules(): array
    {
        return [
            '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)
    {
        // Check for duplicate project+user
        $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)
                    ->exists();

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