import 'dart:convert';
import 'dart:io';

import 'package:dart_frog/dart_frog.dart';
import 'package:new_backend/shrink_ray.dart';
import 'package:path/path.dart' as path;

Future<Response> onRequest(RequestContext context) async {
  switch (context.request.method) {
    case HttpMethod.put:
    case HttpMethod.delete:
    case HttpMethod.head:
    case HttpMethod.options:
    case HttpMethod.patch:
      return Response(statusCode: 404);
    case HttpMethod.post:
      try {
        final reqJson = await context.request.body();
        final data = jsonDecode(reqJson) as Map<String, dynamic>;
        final url = data['url'] as String?;
        if (url == null) {
          return Response(statusCode: 401, body: 'Missing url');
        }
        await Future<void>.delayed(const Duration(seconds: 2));
        final res = ShrinkRay.shrinkUrl(url);
        switch (res.status) {
          case Status.ok:
            shrunkUrls[res.content] = url;
            return Response(
              body: jsonEncode(
                {'url': 'http://localhost:8080/u/${res.content}'},
              ),
            );
          case Status.error:
            return Response(statusCode: 401, body: res.content);
        }
      } catch (err, st) {
        print(st);
        print(err);
        return Response(statusCode: 500, body: 'Unexpected error occurred');
      }
    case HttpMethod.get:
      final file = File(path.join(Directory.current.path, 'public', 'index.html'));
      if (!file.existsSync()) {
        return Response(body: 'Index Not found');
      }
      final indexHtml = file.readAsStringSync();

      return Response(body: indexHtml, headers: {'Content-Type': 'text/html'});
  }
}
