import 'package:firebase_data_connect/firebase_data_connect.dart' as fdc;
import 'package:krow_data_connect/krow_data_connect.dart';
import 'package:krow_domain/krow_domain.dart';
import '../../domain/repositories/home_repository_interface.dart';

/// Implementation of [HomeRepositoryInterface] that delegates to [HomeRepositoryMock].
///
/// This implementation resides in the data layer and acts as a bridge between the
/// domain layer and the data source (in this case, a mock from data_connect).
class HomeRepositoryImpl implements HomeRepositoryInterface {
  final HomeRepositoryMock _mock;
  final ExampleConnector _dataConnect;

  /// Creates a [HomeRepositoryImpl].
  ///
  /// Requires a [HomeRepositoryMock] to perform data operations.
  HomeRepositoryImpl(this._mock, this._dataConnect);

  @override
  Future<HomeDashboardData> getDashboardData() {
    return _mock.getDashboardData();
  }

  @override
  UserSessionData getUserSessionData() {
    final (String businessName, String? photoUrl) = _mock.getUserSession();
    return UserSessionData(
      businessName: businessName,
      photoUrl: photoUrl,
    );
  }

  @override
  Future<List<ReorderItem>> getRecentReorders() async {
    final String? businessId = ClientSessionStore.instance.session?.business?.id;
    if (businessId == null || businessId.isEmpty) {
      return const <ReorderItem>[];
    }

    final DateTime now = DateTime.now();
    final DateTime start = now.subtract(const Duration(days: 30));
    final fdc.Timestamp startTimestamp = _toTimestamp(start);
    final fdc.Timestamp endTimestamp = _toTimestamp(now);

    final fdc.QueryResult<
        ListShiftRolesByBusinessDateRangeCompletedOrdersData,
        ListShiftRolesByBusinessDateRangeCompletedOrdersVariables> result =
        await _dataConnect.listShiftRolesByBusinessDateRangeCompletedOrders(
          businessId: businessId,
          start: startTimestamp,
          end: endTimestamp,
        ).execute();

    print(
      'Home reorder: completed shiftRoles=${result.data.shiftRoles.length}',
    );

    return result.data.shiftRoles.map((
      ListShiftRolesByBusinessDateRangeCompletedOrdersShiftRoles shiftRole,
    ) {
      print(
        'Home reorder item: orderId=${shiftRole.shift.order.id} '
        'shiftId=${shiftRole.shiftId} roleId=${shiftRole.roleId} '
        'orderType=${shiftRole.shift.order.orderType.stringValue} '
        'hours=${shiftRole.hours} count=${shiftRole.count}',
      );
      final String location =
          shiftRole.shift.location ??
          shiftRole.shift.locationAddress ??
          '';
      final String type = shiftRole.shift.order.orderType.stringValue;
      return ReorderItem(
        orderId: shiftRole.shift.order.id,
        title: '${shiftRole.role.name} - ${shiftRole.shift.title}',
        location: location,
        hourlyRate: shiftRole.role.costPerHour,
        hours: shiftRole.hours ?? 0,
        workers: shiftRole.count,
        type: type,
      );
    }).toList();
  }

  fdc.Timestamp _toTimestamp(DateTime date) {
    final int millis = date.millisecondsSinceEpoch;
    final int seconds = millis ~/ 1000;
    final int nanos = (millis % 1000) * 1000000;
    return fdc.Timestamp(nanos, seconds);
  }
}
