import 'package:drift/drift.dart';
import 'package:niogu_app/core/database/app_database.dart';
import 'package:niogu_app/core/enums/sync_status.dart';
import 'package:niogu_app/core/enums/table_type.dart';

class CustomSyncQueue {
  static void addToSyncQueue({
    required TableType type,
    required String id,
    required SyncAction action,
    required Batch batch,
    required $SyncQueuesTable syncQueues,
    required Map<String, dynamic> data,
  }) {
    final payload = SyncPayload(
      table: type.type,
      localId: id,
      action: action.action,
      data: data,
    ).toJson();

    batch.insert(
      syncQueues,
      SyncQueuesCompanion(
        tableType: Value(type.type),
        tableLocalId: Value(id),
        action: Value(action.action),
        status: Value(SyncStatus.dirty.status),
        payload: Value(payload),
      ),
    );
  }

  static void updateSyncQueue({
    required TableType type,
    required String id,
    required SyncAction action,
    required Batch batch,
    required $SyncQueuesTable syncQueues,
    required Map<String, dynamic> data,
  }) {
    final payload = SyncPayload(
      table: type.type,
      localId: id,
      action: action.action,
      data: data,
    ).toJson();

    batch.update(
      syncQueues,
      SyncQueuesCompanion(
        tableType: Value(type.type),
        tableLocalId: Value(id),
        action: Value(action.action),
        status: Value(SyncStatus.dirty.status),
        payload: Value(payload),
      ),
    );
  }
}

class SyncPayload {
  final String table;
  final String localId;
  final String action;
  final Map<String, dynamic> data;

  SyncPayload({
    required this.table,
    required this.localId,
    required this.action,
    required this.data,
  });

  Map<String, dynamic> toJson() => {
    'table': table,
    'local_id': localId,
    'action': action,
    'data': data,
  };
}
