import 'dart:io';
import 'package:backend/extensions/request_context.dart';
import 'package:backend/store.dart';
import 'package:dart_frog/dart_frog.dart';
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
import 'package:shared_models/models/user.dart';
import 'package:uuid/uuid.dart';

Future<Response> onRequest(RequestContext context) async {
  // Only allow POST requests
  if (context.request.method != HttpMethod.post) {
    return Response(statusCode: HttpStatus.methodNotAllowed);
  }

  try {
    // Generate a new user ID
    final userId = const Uuid().v4();

    // Create JWT token
    final jwt = JWT(
      {
        'userId': userId,
        'iat': DateTime.now().millisecondsSinceEpoch,
      },
    );

    // Sign the JWT token (store this secret in environment variables in production)
    final token = jwt.sign(
      SecretKey(jwtSecret),
      expiresIn: const Duration(days: 30), // Token expires in 30 days
    );

    // Create new user
    final user = User(
      id: userId,
      token: token,
      createdAt: DateTime.now(),
    );

    // Store user in memory
    MemoryStore.addUser(user);

    // Return the user credentials
    return Response.json(
      body: {
        'userId': userId,
        'token': token,
      },
    );
  } catch (e) {
    return Response.json(
      statusCode: HttpStatus.internalServerError,
      body: {'error': e.toString()},
    );
  }
}
