import 'package:sqflite/sqflite.dart';

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

class TaxSettingRepository {
  TaxSettingRepository();

  final DatabaseHelper _dbHelper = DatabaseHelper();

  Future<TaxSetting> fetchCurrentSetting() async {
    final db = await _dbHelper.database;
    final rows = await db.query('tax_settings', orderBy: 'updated_at DESC', limit: 1);
    if (rows.isEmpty) {
      final now = DateTime.now();
      final defaultSetting = TaxSetting(id: 'default', rate: 0.1, roundingMode: 'round', updatedAt: now);
      await db.insert('tax_settings', defaultSetting.toMap());
      return defaultSetting;
    }
    return TaxSetting.fromMap(rows.first);
  }

  Future<void> saveSetting(TaxSetting setting) async {
    final db = await _dbHelper.database;
    await db.insert('tax_settings', setting.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
  }
}
