import 'dart:convert'; import 'package:drift/drift.dart'; import 'package:http/http.dart' as http; import '../database/daos/agenti_dao.dart'; import '../database/daos/parametri_dao.dart'; import '../database/database.dart'; import '../database/tables/parametri.dart'; import '../core/constants.dart'; import 'api_service.dart'; class AuthService { final AgentiDao _agentiDao; final ApiService _apiService; final ParametriDao _parametriDao; AuthService(this._agentiDao, this._apiService, this._parametriDao); Future login(String code, String password) async { return _agentiDao.authenticate(code, password); } Future loginRemote(String code, String password) async { final url = await _parametriDao.read(AppConstants.kUrlParam); if (url == null || url.isEmpty) { throw Exception('URL del backend non configurato'); } final uri = Uri.parse('$url/rest/auth/agent-login'); final response = await http .post( uri, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: jsonEncode({'codAgente': code, 'password': password}), ) .timeout(const Duration(seconds: 30)); final resp = jsonDecode(response.body) as Map; if (resp['token'] != null) { return resp['token'] as String; } throw Exception(resp['message'] ?? 'Autenticazione remota fallita'); } Future checkRemoteAgent(String code) async { try { final resp = await _apiService.get('/rest/agente/esisteNew/$code'); return resp['status'] == 0; } catch (_) { return false; } } Future initializeAgent({ required int idAgente, required String codAgente, required String pwd, String? ragioneSociale, required String url, }) async { await _parametriDao.set(AppConstants.kUrlParam, url); await _agentiDao.insertAgente( AgentiCompanion( idAgente: Value(idAgente), codAgente: Value(codAgente), pwd: Value(pwd), ragioneSociale: Value(ragioneSociale ?? codAgente), attivo: const Value(1), ), ); } Future getSavedUrl() => _parametriDao.read(AppConstants.kUrlParam); Future isInitialized() async { final count = await _agentiDao.countAgenti(); final url = await _parametriDao.read(AppConstants.kUrlParam); return count > 0 && url != null && url.isNotEmpty; } }