import 'package:sqflite/sqflite.dart';

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

class SalesEntryRepository {
  SalesEntryRepository();

  final DatabaseHelper _dbHelper = DatabaseHelper();

  Future<void> upsertEntry(SalesEntry entry) async {
    final db = await _dbHelper.database;
    await db.transaction((txn) async {
      await txn.insert('sales_entries', entry.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
      await txn.delete('sales_line_items', where: 'sales_entry_id = ?', whereArgs: [entry.id]);
      for (final item in entry.items) {
        await txn.insert('sales_line_items', item.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
      }
    });
  }

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

  Future<List<SalesEntry>> fetchEntries({SalesEntryStatus? 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(
      'sales_entries',
      where: whereClauses.isNotEmpty ? whereClauses.join(' AND ') : null,
      whereArgs: whereClauses.isNotEmpty ? whereArgs : null,
      orderBy: 'issue_date DESC, updated_at DESC',
      limit: limit,
    );
    final result = <SalesEntry>[];
    for (final row in rows) {
      final items = await _fetchItems(db, row['id'] as String);
      result.add(SalesEntry.fromMap(row, items: items));
    }
    return result;
  }

  Future<void> deleteEntry(String id) async {
    final db = await _dbHelper.database;
    await db.transaction((txn) async {
      await txn.delete('sales_line_items', where: 'sales_entry_id = ?', whereArgs: [id]);
      await txn.delete('sales_entry_sources', where: 'sales_entry_id = ?', whereArgs: [id]);
      await txn.delete('sales_receipt_links', where: 'sales_entry_id = ?', whereArgs: [id]);
      await txn.delete('sales_entries', where: 'id = ?', whereArgs: [id]);
    });
  }

  Future<void> upsertSources(String salesEntryId, List<SalesEntrySource> sources) async {
    final db = await _dbHelper.database;
    await db.transaction((txn) async {
      await txn.delete('sales_entry_sources', where: 'sales_entry_id = ?', whereArgs: [salesEntryId]);
      for (final source in sources) {
        await txn.insert('sales_entry_sources', source.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
      }
    });
  }

  Future<List<SalesEntrySource>> fetchSources(String salesEntryId) async {
    final db = await _dbHelper.database;
    final rows = await db.query('sales_entry_sources', where: 'sales_entry_id = ?', whereArgs: [salesEntryId], orderBy: 'imported_at DESC');
    return rows.map(SalesEntrySource.fromMap).toList();
  }

  Future<List<SalesLineItem>> _fetchItems(DatabaseExecutor db, String entryId) async {
    final rows = await db.query('sales_line_items', where: 'sales_entry_id = ?', whereArgs: [entryId]);
    return rows.map(SalesLineItem.fromMap).toList();
  }
}
