<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Mail\WelcomeMail;
use App\Models\Subscription;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class EmailVerificationController extends Controller
{
    /**
     * Verify a user's email address via a signed URL.
     *
     * Route: GET /api/email/verify/{id}/{hash}
     * Middleware: signed
     */
    public function verify(Request $request, int $id, string $hash): JsonResponse
    {
        if (! $request->hasValidSignature()) {
            return response()->json([
                'message' => 'This verification link is invalid or has expired.',
            ], 403);
        }

        $user = User::findOrFail($id);

        if (! hash_equals(sha1($user->getEmailForVerification()), $hash)) {
            return response()->json([
                'message' => 'This verification link does not match your account.',
            ], 403);
        }

        if ($user->hasVerifiedEmail()) {
            return response()->json([
                'message' => 'Your email address is already verified.',
                'already_verified' => true,
            ]);
        }

        $user->markEmailAsVerified();

        // Send branded welcome email now that the address is confirmed
        try {
            $org          = $user->organization;
            $subscription = $org ? Subscription::where('organization_id', $org->id)->latest()->first() : null;

            Mail::to($user->email)->send(new WelcomeMail(
                userName:      $user->name,
                userEmail:     $user->email,
                orgName:       $org?->name ?? config('app.name'),
                role:          'Organisation Owner',
                loginUrl:      config('app.url') . '/login',
                plainPassword: null,
                isOrgOwner:    true,
                trialEndsAt:   $subscription?->trial_ends_at?->toIso8601String(),
            ));
        } catch (\Throwable $e) {
            Log::warning('Failed to send welcome email after verification.', [
                'user_id' => $user->id,
                'error'   => $e->getMessage(),
            ]);
        }

        return response()->json([
            'message' => 'Your Account has been Verified! Your welcome email is on its way.',
        ]);
    }

    /**
     * Resend the email verification notification to the authenticated user.
     *
     * Route: POST /api/email/resend
     * Middleware: auth:sanctum, throttle:6,1
     */
    public function resend(Request $request): JsonResponse
    {
        $user = $request->user();

        if ($user->hasVerifiedEmail()) {
            return response()->json([
                'message' => 'Your email address is already verified.',
            ]);
        }

        $user->sendEmailVerificationNotification();

        return response()->json([
            'message' => 'A new verification link has been sent to ' . $user->email . '.',
        ]);
    }
}
