import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
import '../database/database_provider.dart';
import '../middleware/auth_middleware.dart';
import '../middleware/request_logger.dart';
import 'dart:convert';

class GeoRoutes {
  final DatabaseProvider database;

  GeoRoutes(this.database);

  Router get routes {
    final router = Router();
    router.put('/geo', AuthMiddleware(_updatePosition).call);
    router.post('/share', AuthMiddleware(_createShare).call);
    return router;
  }

  Future<Response> _updatePosition(Request request, String login) async {
    final stopwatch = Stopwatch()..start();
    final id = request.url.queryParameters['id']!;
    final body = await request.readAsString();
    final data = jsonDecode(body);

    final x = data['x'];
    final y = data['y'];

    await database.updatePosition(id, x, y);
    await database.createLog(login, 'Updated position id=$id');
    stopwatch.stop();
    final response = Response(200, body: jsonEncode({'message': 'Position updated'}), headers: {'Content-Type': 'application/json'});
    logRequest(method: 'PUT', url: '/geo', status: 200, duration: stopwatch.elapsed, body: body, responseHeaders: response.headers);
    return response;
  }

  Future<Response> _createShare(Request request, String login) async {
    final stopwatch = Stopwatch()..start();
    final body = await request.readAsString();
    final data = jsonDecode(body);

    final x = data['x'];
    final y = data['y'];

    final position = await database.createPosition(x, y);
    final shareId = database.createShareId(position.id);

    await database.createLog(login, 'Created share link geo_id=${position.id}');
    stopwatch.stop();
    final response = Response(201, body: jsonEncode({
      'geo_id': position.id,
      'share_id': shareId
    }), headers: {'Content-Type': 'application/json'});
    logRequest(method: 'POST', url: '/share', status: 201, duration: stopwatch.elapsed, body: body, responseHeaders: response.headers);
    return response;
  }
}