<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PortalUser;
use App\Services\PortalUserService;
use Illuminate\Http\JsonResponse;

class PortalUserController extends Controller
{
    public function __construct(
        private readonly PortalUserService $portalUserService
    ) {}

    /**
     * Display a listing of portal users.
     */
    public function index(): JsonResponse
    {
        try {
            $portalUsers = PortalUser::orderBy('created_at', 'desc')->get();

            return response()->json([
                'success' => true,
                'data' => $portalUsers->map(fn ($user) => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'role' => $user->role,
                    'password_set' => $user->hasSetPassword(),
                    'invitation_sent_at' => $user->invitation_sent_at?->toIso8601String(),
                    'password_set_at' => $user->password_set_at?->toIso8601String(),
                    'created_at' => $user->created_at->toIso8601String(),
                ]),
            ]);
        } catch (\Exception $e) {
            \Log::error('Error fetching portal users: ' . $e->getMessage(), [
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while fetching portal users.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Display the specified portal user.
     */
    public function show(PortalUser $portalUser): JsonResponse
    {
        return response()->json([
            'success' => true,
            'data' => [
                'id' => $portalUser->id,
                'name' => $portalUser->name,
                'email' => $portalUser->email,
                'role' => $portalUser->role,
                'password_set' => $portalUser->hasSetPassword(),
                'invitation_sent_at' => $portalUser->invitation_sent_at?->toIso8601String(),
                'password_set_at' => $portalUser->password_set_at?->toIso8601String(),
                'email_verified_at' => $portalUser->email_verified_at?->toIso8601String(),
                'created_at' => $portalUser->created_at->toIso8601String(),
                'updated_at' => $portalUser->updated_at->toIso8601String(),
            ],
        ]);
    }

    /**
     * Resend invitation to a portal user.
     */
    public function resendInvitation(\App\Http\Requests\ResendInvitationRequest $request): JsonResponse
    {
        $portalUser = PortalUser::findOrFail($request->validated('portal_user_id'));

        $this->portalUserService->resendInvitation($portalUser);

        return response()->json([
            'success' => true,
            'message' => 'Invitation email resent successfully.',
            'data' => [
                'invitation_sent_at' => $portalUser->fresh()->invitation_sent_at->toIso8601String(),
            ],
        ]);
    }
}

