import 'package:sqflite/sqflite.dart';

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

class SalesOrderRepository {
  SalesOrderRepository();

  final DatabaseHelper _dbHelper = DatabaseHelper();

  Future<void> upsertOrder(SalesOrder order) async {
    final db = await _dbHelper.database;
    await db.transaction((txn) async {
      await txn.insert('sales_orders', order.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
      await txn.delete('sales_order_items', where: 'order_id = ?', whereArgs: [order.id]);
      for (final item in order.items) {
        await txn.insert('sales_order_items', item.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
      }
    });
  }

  Future<List<SalesOrder>> fetchOrders({SalesOrderStatus? 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 orders = await db.query(
      'sales_orders',
      where: whereClauses.isNotEmpty ? whereClauses.join(' AND ') : null,
      whereArgs: whereClauses.isNotEmpty ? whereArgs : null,
      orderBy: 'order_date DESC',
      limit: limit,
    );

    final result = <SalesOrder>[];
    for (final row in orders) {
      final items = await _fetchItemsByOrderId(db, row['id'] as String);
      result.add(SalesOrder.fromMap(row, items: items));
    }
    return result;
  }

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

  Future<void> deleteOrder(String id) async {
    final db = await _dbHelper.database;
    await db.transaction((txn) async {
      await txn.delete('sales_order_items', where: 'order_id = ?', whereArgs: [id]);
      await txn.delete('sales_orders', where: 'id = ?', whereArgs: [id]);
    });
  }

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

  Future<List<SalesOrderItem>> _fetchItemsByOrderId(DatabaseExecutor db, String orderId) async {
    final rows = await db.query(
      'sales_order_items',
      where: 'order_id = ?',
      whereArgs: [orderId],
      orderBy: 'sort_index ASC, rowid ASC',
    );
    return rows.map(SalesOrderItem.fromMap).toList();
  }
}
