<?php

namespace App\Http\Requests;

use App\Enums\Permission;
use App\Enums\WorkspaceUserRole;
use App\Models\TeamInvitation;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;

class InviteTeamMemberRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        $workspaceUser = $this->user()->currentWorkspaceUser();

        if ($workspaceUser->role->is(WorkspaceUserRole::Owner)) {
            return true;
        }

        if ($workspaceUser->role->is(WorkspaceUserRole::Manager)) {
            return (bool) ($workspaceUser->permissions[Permission::CanManageTeam] ?? false);
        }

        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'email' => ['required', 'email', 'max:255'],
            'role' => ['required', 'in:manager,worker'],
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $workspaceId = session('current_workspace_id');
            $email = $this->input('email');

            // Check if email is already a member of the workspace
            $alreadyMember = \App\Models\Workspace::find($workspaceId)
                ?->users()
                ->where('email', $email)
                ->exists();

            if ($alreadyMember) {
                $validator->errors()->add('email', 'Cet utilisateur fait déjà partie de l\'équipe.');
            }

            // Check for existing active invitation
            $existingInvitation = TeamInvitation::where('workspace_id', $workspaceId)
                ->where('email', $email)
                ->whereNull('accepted_at')
                ->where('expires_at', '>', now())
                ->exists();

            if ($existingInvitation) {
                $validator->errors()->add('email', 'Une invitation est déjà en cours pour cette adresse email.');
            }
        });
    }

    /**
     * Handle a failed authorization attempt.
     */
    protected function failedAuthorization(): void
    {
        abort(404);
    }
}
