import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../data/repository/news_repository.dart';
import '../data/models/region_news.dart';

part 'news_controller.g.dart';

/// The news controller
@riverpod
class NewsController extends _$NewsController {
  @override
  Future<RegionNews> build() async {
    try {
      final String newsResponse = await NewsRepository().fetchNews();
      final Map<String, dynamic> jsonData = json.decode(newsResponse);
      final RegionNews news = RegionNews.fromJson(jsonData);
      return news;
    } catch (e) {
      rethrow;
    }
  }

  /// Append the next page of news to the current news list
  Future<void> appendPage() async {
    try {
      final RegionNews currentNews =
          state.asData?.value ?? const RegionNews(news: []);
      final newsResponse =
          await NewsRepository().fetchNewsPage(currentNews.nextPage ?? 'null');
      final Map<String, dynamic> jsonData = jsonDecode(newsResponse);
      final RegionNews nextNews = RegionNews.fromJson(jsonData);
      final RegionNews appendNews =
          currentNews.copyWith(nextPage: nextNews.nextPage, news: [
        ...currentNews.news,
        ...nextNews.news,
      ]);
      state = AsyncData(appendNews);
    } catch (e) {
      debugPrint(e.toString());
    }
  }
}
