import 'package:bloc/bloc.dart';
import 'package:dio/dio.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:hoshan/core/services/api/courses_services.dart';
import 'package:hoshan/data/model/posts_model.dart';

part 'posts_state.dart';

class PostsCubit extends Cubit<PostsState> {
  PostsCubit() : super(PostsInitial());

  void getLastPosts() async {
    print('🔵 getLastPosts called');
    // Disabled enabled.json check - always show posts
    // try {
    //   final check = await CoursesServices.dio.get('/enabled.json');
    //   print('� enabled.json: ${check.data}');
    //   if (check.data == false) {
    //     emit(PostsFail());
    //     return;
    //   }
    // } catch (e) {
    //   // Ignore enabled.json check errors
    // }
    emit(PostsLoading());
    try {
      final posts = <PostsModel>[];

      final response = await CoursesServices.dio.get(
        CoursesServices.getPosts,
      );
      
      print('🟢 API Response: ${response.statusCode}');
      print('🟢 Data type: ${response.data.runtimeType}');
      print('🟢 Data length: ${response.data?.length}');

      response.data.forEach((v) {
        posts.add(PostsModel.fromJson(v));
      });

      if (kDebugMode) {
        print('✅ Fetched ${posts.length} posts from WordPress');
      }

      emit(PostsSuccess(posts: posts));
    } on DioException catch (e) {
      emit(PostsFail());
      if (kDebugMode) {
        print('❌ Posts Error: ${e.message}');
      }
    } catch (e) {
      emit(PostsFail());
      if (kDebugMode) {
        print('❌ Posts Error: $e');
      }
    }
  }
}
