import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; const _kWebcontrolUrl = 'http://192.168.10.145:3002'; const _kTimeout = Duration(seconds: 10); // ── Modelos ──────────────────────────────────────────────────────────────── class Empresa { final String dba; final String nombre; const Empresa({required this.dba, required this.nombre}); factory Empresa.fromMap(Map m) => Empresa( dba: (m['dba'] ?? m['db'] ?? '').toString(), nombre: (m['nombre'] ?? m['name'] ?? m['empresa'] ?? m['dba'] ?? '') .toString(), ); } class AuthResult { final String jwt; final String apiKey; final String dbTenant; final Map usuarioData; const AuthResult({ required this.jwt, required this.apiKey, required this.dbTenant, required this.usuarioData, }); } class AuthException implements Exception { final String message; const AuthException(this.message); @override String toString() => message; } // ── Servicio ─────────────────────────────────────────────────────────────── class AuthService { /// Paso 1 — obtiene la lista de empresas del email. /// Retorna `null` si no hay conexión (fallback a modo offline). /// Lanza [AuthException] si las credenciales son incorrectas. static Future?> getEmpresas( String email, String password) async { try { final res = await http .post( Uri.parse('$_kWebcontrolUrl/api/auth/empresas'), headers: {'Content-Type': 'application/json'}, body: jsonEncode({'email': email, 'password': password}), ) .timeout(_kTimeout); final body = _decodeBody(res.body); if (res.statusCode == 401 || res.statusCode == 403) { throw AuthException( body['message'] as String? ?? 'Credenciales incorrectas'); } if (res.statusCode != 200) { throw AuthException(body['message'] as String? ?? 'Error del servidor (${res.statusCode})'); } final lista = body['empresas'] as List? ?? []; return lista .map((e) => Empresa.fromMap(e as Map)) .toList(); } on AuthException { rethrow; } on SocketException { return null; } on TimeoutException { return null; } on HttpException { return null; } catch (_) { return null; } } /// Paso 2 — obtiene JWT + apiKey + db_tenant. /// Retorna `null` si no hay conexión. /// Lanza [AuthException] si las credenciales son incorrectas. static Future login( String email, String password, String dba) async { try { final res = await http .post( Uri.parse('$_kWebcontrolUrl/api/auth/login'), headers: {'Content-Type': 'application/json'}, body: jsonEncode({'email': email, 'password': password, 'dba': dba}), ) .timeout(_kTimeout); final body = _decodeBody(res.body); if (res.statusCode == 401 || res.statusCode == 403) { throw AuthException( body['message'] as String? ?? 'Credenciales incorrectas'); } if (res.statusCode != 200) { throw AuthException(body['message'] as String? ?? 'Error del servidor (${res.statusCode})'); } return AuthResult( jwt: (body['token'] ?? body['jwt'] ?? '').toString(), apiKey: (body['apiKey'] ?? body['api_key'] ?? '').toString(), dbTenant: (body['db_tenant'] ?? body['dbTenant'] ?? dba).toString(), usuarioData: (body['usuario'] as Map?) ?? (body['user'] as Map?) ?? body, ); } on AuthException { rethrow; } on SocketException { return null; } on TimeoutException { return null; } on HttpException { return null; } catch (_) { return null; } } static Map _decodeBody(String raw) { try { return jsonDecode(raw) as Map; } catch (_) { return {}; } } }