import 'package:sqflite/sqflite.dart';

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

class SalesReceiptRepository {
  SalesReceiptRepository();

  final DatabaseHelper _dbHelper = DatabaseHelper();

  Future<void> upsertReceipt(SalesReceipt receipt, List<SalesReceiptLink> links) async {
    final db = await _dbHelper.database;
    await db.transaction((txn) async {
      await txn.insert('sales_receipts', receipt.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
      await txn.delete('sales_receipt_links', where: 'receipt_id = ?', whereArgs: [receipt.id]);
      for (final link in links) {
        await txn.insert('sales_receipt_links', link.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
      }
    });
  }

  Future<List<SalesReceipt>> fetchReceipts({DateTime? startDate, DateTime? endDate}) async {
    final db = await _dbHelper.database;
    final whereClauses = <String>[];
    final args = <Object?>[];
    if (startDate != null) {
      whereClauses.add('payment_date >= ?');
      args.add(startDate.toIso8601String());
    }
    if (endDate != null) {
      whereClauses.add('payment_date <= ?');
      args.add(endDate.toIso8601String());
    }
    final rows = await db.query(
      'sales_receipts',
      where: whereClauses.isEmpty ? null : whereClauses.join(' AND '),
      whereArgs: whereClauses.isEmpty ? null : args,
      orderBy: 'payment_date DESC, updated_at DESC',
    );
    return rows.map(SalesReceipt.fromMap).toList();
  }

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

  Future<List<SalesReceiptLink>> fetchLinks(String receiptId) async {
    final db = await _dbHelper.database;
    final rows = await db.query('sales_receipt_links', where: 'receipt_id = ?', whereArgs: [receiptId]);
    return rows.map(SalesReceiptLink.fromMap).toList();
  }

  Future<void> deleteReceipt(String id) async {
    final db = await _dbHelper.database;
    await db.transaction((txn) async {
      await txn.delete('sales_receipt_links', where: 'receipt_id = ?', whereArgs: [id]);
      await txn.delete('sales_receipts', where: 'id = ?', whereArgs: [id]);
    });
  }

  Future<Map<String, int>> fetchAllocatedTotals(Iterable<String> entryIds) async {
    final ids = entryIds.where((id) => id.isNotEmpty).toSet().toList();
    if (ids.isEmpty) return {};
    final db = await _dbHelper.database;
    final placeholders = List.filled(ids.length, '?').join(',');
    final rows = await db.rawQuery(
      'SELECT sales_entry_id, SUM(allocated_amount) AS total FROM sales_receipt_links WHERE sales_entry_id IN ($placeholders) GROUP BY sales_entry_id',
      ids,
    );
    final result = <String, int>{};
    for (final row in rows) {
      final entryId = row['sales_entry_id'] as String?;
      if (entryId == null) continue;
      result[entryId] = (row['total'] as num?)?.toInt() ?? 0;
    }
    return result;
  }
}
