import 'dart:convert';

import 'package:cinema/feature/poster/domain/poster_request.schema.dart';
import 'package:injectable/injectable.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';

part 'poster.service.g.dart';

@injectable
class PosterService {
  @Route.get('/')
  Future<Response> getRoot(Request request) async {
    return Response.ok('deprecated poster endpoint. use POST /poster instead');
  }

  @Route.post('/')
  Future<Response> postRoot(Request request) async {
    final payload = await request.readAsString();
    final body = jsonDecode(payload);
    final params = posterSchema.safeParse(body);
    if (!params.success) {
      return Response(
        400,
        body: jsonEncode({
          'error': 'Invalid request',
          'details': params.error?.messages,
        }),
        headers: {'Content-Type': 'application/json'},
      );
    }
    return Response.ok(jsonEncode(params.data), headers: {'Content-Type': 'application/json'});
  }

  Router get router => _$PosterServiceRouter(this);
}
