<?php

namespace App\Http\Controllers\Api\TenantAuth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\TenantAdminForgotPasswordRequest;
use App\Http\Requests\Auth\TenantAdminResetPasswordRequest;
use App\Models\EventMember;
use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class TenantAdminPasswordResetController extends Controller
{
    public function requestLink(TenantAdminForgotPasswordRequest $request): JsonResponse
    {
        $email = $request->string('email')->trim()->value();

        $user = User::query()->where('email', $email)->first();

        if (! $user || ! $this->canAccessEventAdmin($user)) {
            return $this->genericSuccessResponse();
        }

        Password::sendResetLink([
            'email' => $email,
        ]);

        return $this->genericSuccessResponse();
    }

    public function reset(TenantAdminResetPasswordRequest $request): JsonResponse
    {
        $status = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function (User $user) use ($request) {
                $this->ensureUserCanReset($user);

                $user->forceFill([
                    'password' => Hash::make($request->string('password')->value()),
                    'remember_token' => Str::random(60),
                ])->save();

                event(new PasswordReset($user));
            }
        );

        if ($status === Password::PasswordReset) {
            return response()->json([
                'status' => __($status),
            ]);
        }

        throw ValidationException::withMessages([
            'email' => [__($status)],
        ]);
    }

    private function genericSuccessResponse(): JsonResponse
    {
        return response()->json([
            'status' => __('passwords.sent'),
        ]);
    }

    private function ensureUserCanReset(User $user): void
    {
        if ($this->canAccessEventAdmin($user)) {
            return;
        }

        throw ValidationException::withMessages([
            'email' => [trans('auth.not_authorized')],
        ]);
    }

    private function canAccessEventAdmin(User $user): bool
    {
        if (in_array($user->role, ['tenant_admin', 'admin', 'super_admin', 'superadmin'], true)) {
            return true;
        }

        if ($user->role === 'member' && $this->userHasCollaboratorMembership($user)) {
            return true;
        }

        return false;
    }

    private function userHasCollaboratorMembership(User $user): bool
    {
        if (! $user->tenant_id) {
            return false;
        }

        return EventMember::query()
            ->where('tenant_id', $user->tenant_id)
            ->where(function ($query) use ($user) {
                $query->where('user_id', $user->id)
                    ->orWhere('email', $user->email);
            })
            ->whereIn('status', ['active', 'invited'])
            ->exists();
    }
}
