import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/models.dart';
import '../database/db_helper.dart';

class AuthService extends ChangeNotifier {
  UserModel? _user;
  DomicilioModel? _domicilio;
  bool _loading = true;

  UserModel? get currentUser => _user;
  DomicilioModel? get primaryDomicilio => _domicilio;
  bool get isLoggedIn => _user != null;
  bool get loading => _loading;
  String get rol => _user?.rol ?? '';

  AuthService() { _checkSession(); }

  Future<void> _checkSession() async {
    final p = await SharedPreferences.getInstance();
    final id = p.getInt('user_id');
    if (id != null) {
      _user = await DbHelper.getUserById(id);
      if (_user?.rol == 'CIUDADANO') {
        _domicilio = await DbHelper.getPrimaryDomicilio(id);
      }
    }
    _loading = false;
    notifyListeners();
  }

  Future<String?> login(String email, String password) async {
    final user = await DbHelper.getUserByEmail(email.trim().toLowerCase());
    if (user == null) return 'Correo no registrado';
    if (user.password != password) return 'Contraseña incorrecta';
    _user = user;
    if (user.rol == 'CIUDADANO') {
      _domicilio = await DbHelper.getPrimaryDomicilio(user.id!);
    }
    final p = await SharedPreferences.getInstance();
    await p.setInt('user_id', user.id!);
    notifyListeners();
    return null;
  }

  Future<String?> register({required String nombre, required String email,
      required String password, required String calle, required String colonia,
      required String routeId, required String horarioEstimado}) async {
    final ex = await DbHelper.getUserByEmail(email.trim().toLowerCase());
    if (ex != null) return 'Correo ya registrado';
    final user = UserModel(nombre:nombre.trim(),
        email:email.trim().toLowerCase(), password:password, rol:'CIUDADANO');
    final uid = await DbHelper.insertUser(user);
    await DbHelper.insertDomicilio(DomicilioModel(userId:uid, calle:calle.trim(),
        colonia:colonia, routeId:routeId, horarioEstimado:horarioEstimado));
    _user = await DbHelper.getUserById(uid);
    _domicilio = await DbHelper.getPrimaryDomicilio(uid);
    final p = await SharedPreferences.getInstance();
    await p.setInt('user_id', uid);
    notifyListeners();
    return null;
  }

  Future<void> logout() async {
    _user = null; _domicilio = null;
    final p = await SharedPreferences.getInstance();
    await p.remove('user_id');
    notifyListeners();
  }
}
