import 'package:sqflite/sqflite.dart';

import '../models/shipment_models.dart';
import 'database_helper.dart';

class ShipmentRepository {
  ShipmentRepository();

  final DatabaseHelper _dbHelper = DatabaseHelper();

  Future<void> upsertShipment(Shipment shipment) async {
    final db = await _dbHelper.database;
    await db.transaction((txn) async {
      await txn.insert('shipments', shipment.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
      await txn.delete('shipment_items', where: 'shipment_id = ?', whereArgs: [shipment.id]);
      for (final item in shipment.items) {
        await txn.insert('shipment_items', item.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
      }
    });
  }

  Future<List<Shipment>> fetchShipments({ShipmentStatus? status, int? limit}) async {
    final db = await _dbHelper.database;
    final whereClauses = <String>[];
    final whereArgs = <Object?>[];
    if (status != null) {
      whereClauses.add('status = ?');
      whereArgs.add(status.name);
    }
    final rows = await db.query(
      'shipments',
      where: whereClauses.isNotEmpty ? whereClauses.join(' AND ') : null,
      whereArgs: whereClauses.isNotEmpty ? whereArgs : null,
      orderBy: 'scheduled_ship_date IS NULL, scheduled_ship_date ASC, updated_at DESC',
      limit: limit,
    );
    return Future.wait(rows.map((row) async {
      final items = await _fetchItemsByShipmentId(db, row['id'] as String);
      return Shipment.fromMap(row, items: items);
    }));
  }

  Future<Shipment?> findById(String id) async {
    final db = await _dbHelper.database;
    final rows = await db.query('shipments', where: 'id = ?', whereArgs: [id], limit: 1);
    if (rows.isEmpty) return null;
    final items = await _fetchItemsByShipmentId(db, id);
    return Shipment.fromMap(rows.first, items: items);
  }

  Future<void> deleteShipment(String id) async {
    final db = await _dbHelper.database;
    await db.transaction((txn) async {
      await txn.delete('shipment_items', where: 'shipment_id = ?', whereArgs: [id]);
      await txn.delete('shipments', where: 'id = ?', whereArgs: [id]);
    });
  }

  Future<void> updateStatus({required String shipmentId, required ShipmentStatus status, DateTime? actualShipDate}) async {
    final db = await _dbHelper.database;
    await db.update(
      'shipments',
      {
        'status': status.name,
        'actual_ship_date': actualShipDate?.toIso8601String(),
        'updated_at': DateTime.now().toIso8601String(),
      },
      where: 'id = ?',
      whereArgs: [shipmentId],
    );
  }

  Future<List<ShipmentItem>> _fetchItemsByShipmentId(DatabaseExecutor db, String shipmentId) async {
    final rows = await db.query(
      'shipment_items',
      where: 'shipment_id = ?',
      whereArgs: [shipmentId],
      orderBy: 'rowid ASC',
    );
    return rows.map(ShipmentItem.fromMap).toList();
  }
}
