<?php

namespace App\Http\Responses;

use App\Models\TeamInvitation;
use App\Models\WorkspaceUser;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;

class LoginResponse implements LoginResponseContract
{
    /**
     * Create an HTTP response that represents the object.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function toResponse($request)
    {
        $token = $request->input('invitation')
            ?? $request->session()->pull('pending_invitation_token');

        if ($token) {
            $invitation = TeamInvitation::where('token', $token)->first();
            $user = $request->user();

            if ($invitation && $invitation->isValid() && strtolower($invitation->email) === strtolower($user->email)) {
                $alreadyMember = WorkspaceUser::where('workspace_id', $invitation->workspace_id)
                    ->where('user_id', $user->id)
                    ->exists();

                if (! $alreadyMember) {
                    DB::transaction(function () use ($user, $invitation) {
                        $user->workspaces()->attach($invitation->workspace_id, [
                            'role' => $invitation->role,
                            'permissions' => json_encode(config("permissions.defaults.{$invitation->role}", [])),
                        ]);

                        $invitation->update(['accepted_at' => now()]);
                    });
                } else {
                    session(['current_workspace_id' => $invitation->workspace_id]);

                    return redirect()->intended('/dashboard');
                }

                session(['current_workspace_id' => $invitation->workspace_id]);

                return redirect()->intended('/dashboard');
            }
        }

        // Clean up session token if present but not used
        $request->session()->forget('pending_invitation_token');

        return $request->wantsJson()
            ? new JsonResponse('', 204)
            : redirect()->intended(config('fortify.home'));
    }
}
