import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../api/api_client.dart';
import 'auth_state.dart';

final authProvider =
    StateNotifierProvider<AuthNotifier, WaiterSession?>((ref) {
  return AuthNotifier(ref.watch(apiClientProvider));
});

class AuthNotifier extends StateNotifier<WaiterSession?> {
  AuthNotifier(this._client) : super(null) {
    _restore();
  }

  final ApiClient _client;

  Future<void> _restore() async {
    // Check stored token and validate it's still usable
    final token = await _client.readToken();
    if (token == null || token.isEmpty) return;
    try {
      final res = await _client.dio.get<Map<String, dynamic>>('/api/auth/me');
      final data = res.data?['data'] as Map<String, dynamic>?;
      if (data == null) return;
      // Merge stored token with fetched profile
      final json = {...data, 'accessToken': token};
      state = WaiterSession.fromJson(json);
    } catch (_) {
      // Token expired or network error — stay logged out
    }
  }

  Future<String> sendOtp(String phone) async {
    final res = await _client.dio.post<Map<String, dynamic>>(
      '/api/auth/send-otp',
      data: {'phone': phone},
    );
    final data = res.data?['data'] as Map<String, dynamic>?;
    return (data?['sessionId'] ?? '') as String;
  }

  Future<void> verifyOtp(String phone, String otp) async {
    final res = await _client.dio.post<Map<String, dynamic>>(
      '/api/auth/verify-otp',
      data: {'phone': phone, 'otp': otp},
    );
    final data = res.data?['data'] as Map<String, dynamic>?;
    if (data == null) throw Exception('AUTH_FAILED');
    final session = WaiterSession.fromJson(data);
    await _client.saveToken(session.accessToken);
    state = session;
  }

  Future<void> logout() async {
    await _client.clearToken();
    state = null;
  }
}
