<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\AiBiography\AiBiographyService;
use App\Support\UsernamePolicy;
use Illuminate\Http\JsonResponse;

/**
 * Public read endpoint for a creator's AI biography.
 *
 * GET /api/profile/{username}/ai-biography
 *
 * Returns null data if no visible biography exists (hidden, failed, or not yet generated).
 * Never triggers generation — only serves stored text.
 */
final class ProfileAiBiographyController extends Controller
{
    public function __construct(private readonly AiBiographyService $biographies)
    {
    }

    public function show(string $username): JsonResponse
    {
        $normalized = UsernamePolicy::normalize($username);

        $user = User::query()
            ->whereRaw('LOWER(username) = ?', [$normalized])
            ->where('is_active', true)
            ->whereNull('deleted_at')
            ->firstOrFail();

        $payload = $this->biographies->publicPayload($user);

        return response()->json([
            'data' => $payload,
            'meta' => [
                'username'     => (string) $user->username,
                'generated_at' => now()->toIso8601String(),
            ],
        ]);
    }
}
