import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';

const bool RUN_EXTERNAL_TESTS = bool.fromEnvironment('RUN_EXTERNAL_TESTS');
void main() {
  if (!RUN_EXTERNAL_TESTS) {
    test('External tests disabled', () {}, skip: 'Enable with --dart-define=RUN_EXTERNAL_TESTS=true');
    return;
  }
  final baseUrl = Platform.environment['INTEGRATION_API_BASE_URL'];
  final username = Platform.environment['INTEGRATION_LOGIN_USERNAME'];
  final password = Platform.environment['INTEGRATION_LOGIN_PASSWORD'];

  group('Auth Integration (real API)', () {
    test('health endpoint responds', () async {
      if (baseUrl == null || baseUrl.isEmpty) {
        return; // silently succeed when not configured
      }
      final dio = Dio(BaseOptions(baseUrl: baseUrl));
      final res = await dio.get('/health');
      expect(res.statusCode, inInclusiveRange(200, 204));
    }, tags: ['integration']);

    test('login and get users (requires credentials)', () async {
      if (baseUrl == null || username == null || password == null) {
        return; // silently succeed when not configured
      }
      final dio = Dio(BaseOptions(baseUrl: baseUrl));
      final loginRes = await dio.post('/auth/login', data: {
        'username': username,
        'password': password,
      });
      expect(loginRes.statusCode, inInclusiveRange(200, 204));

      final accessToken = loginRes.data['access_token'] as String?;
      expect(accessToken, isNotNull);

      dio.options.headers['Authorization'] = 'Bearer $accessToken';
      final usersRes = await dio.get('/users');
      expect(usersRes.statusCode, inInclusiveRange(200, 204));
    }, tags: ['integration']);
  });
}
