// lib/core/networks/library_api_service.dart

import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;

import 'api_client.dart';

class LibraryApiService {
  // ============================================================
  // BACKEND CONFIGURATION
  // ============================================================

  static String get _baseUrl {
    // Optional override:
    // flutter run --dart-define=LIBRARY_API_URL=http://SERVER/skill_end/api/library.php
    const configuredUrl = String.fromEnvironment('LIBRARY_API_URL');

    if (configuredUrl.trim().isNotEmpty) {
      return configuredUrl.trim().replaceFirst(RegExp(r'/+$'), '');
    }

    // Android emulator uses 10.0.2.2 to reach the host computer.
    if (!kIsWeb &&
        defaultTargetPlatform == TargetPlatform.android) {
      return 'https://intranet.rockviewuniversity.ac/skill_end/api/library.php';
    }

    // Local web and desktop development.
    return 'https://intranet.rockviewuniversity.ac/skill_end/api/library.php';
  }

  // Query routing works on standard cPanel Apache/PHP installations where
  // PATH_INFO after a .php file may be disabled (causing an Apache 404 before
  // library.php is executed). The backend accepts both this form and PATH_INFO.
  static Uri _uri(String path) {
    final parts = path.split('/').where((part) => part.isNotEmpty).toList();
    if (parts.isEmpty) return Uri.parse(_baseUrl);

    final resource = parts.first;
    String queryValue(String part) {
      try { return Uri.decodeComponent(part); } catch (_) { return part; }
    }
    final query = <String, String>{'resource': resource};

    if (resource == 'students') {
      if (parts.length > 1) query['id'] = queryValue(parts[1]);
      if (parts.length > 2) query['action'] = queryValue(parts[2]);
    } else if (resource == 'borrow-records') {
      if (parts.length > 1) query['action'] = queryValue(parts[1]);
      if (parts.length > 2) query['reference'] = queryValue(parts[2]);
    } else if (parts.length > 1) {
      query['id'] = queryValue(parts[1]);
    }

    return Uri.parse(_baseUrl).replace(queryParameters: query);
  }

  static String _pathId(String value, String label) {
    final cleaned = _requiredText(value, label);
    return Uri.encodeComponent(cleaned);
  }

  // ============================================================
  // HEADERS
  // ============================================================

  static Future<Map<String, String>> _headers() async {
    final headers = Map<String, String>.from(
      await ApiClient.getHeaders(),
    );

    // Preserve authentication headers while normalising JSON headers.
    headers.removeWhere((key, _) {
      final name = key.toLowerCase();
      return name == 'content-type' || name == 'accept';
    });

    headers['Content-Type'] = 'application/json; charset=UTF-8';
    headers['Accept'] = 'application/json';

    return headers;
  }

  // ============================================================
  // VALIDATION
  // ============================================================

  static String _requiredText(
    dynamic value,
    String label, {
    bool stringOnly = false,
  }) {
    if (value is! String && (stringOnly || value is! num)) {
      throw Exception('$label is required.');
    }

    final text = value.toString().trim();

    if (text.isEmpty || text.toLowerCase() == 'null') {
      throw Exception('$label is required.');
    }

    return text;
  }

  static DateTime _requiredDate(dynamic value, String label) {
    final text = _requiredText(
      value,
      label,
      stringOnly: true,
    );

    final parsed = DateTime.tryParse(text);

    if (parsed == null) {
      throw Exception('$label must be a valid ISO 8601 date.');
    }

    return parsed;
  }

  // ============================================================
  // RESPONSE HANDLING
  // ============================================================

  static String _extractError(http.Response response) {
    // Prefer the specific error supplied by PHP.
    try {
      final data = jsonDecode(response.body);

      if (data is Map) {
        for (final key in ['detail', 'message', 'error']) {
          final value = data[key];

          if (value == null) continue;

          final message = value.toString().trim();

          if (message.isNotEmpty &&
              message.toLowerCase() != 'null') {
            return message;
          }
        }
      }
    } catch (_) {
      // The server may have returned HTML or plain text.
    }

    if (response.statusCode == 404) {
      return 'Library API route not found. '
          'Check the backend URL and library.php location.';
    }

    if (response.statusCode == 401) {
      return 'Your session has expired. Please sign in again.';
    }

    if (response.statusCode == 403) {
      return 'You do not have permission to perform this action.';
    }

    var message = response.body
        .replaceAll(RegExp(r'<[^>]*>'), '')
        .replaceAll(RegExp(r'\s+'), ' ')
        .trim();

    if (message.isEmpty) {
      return 'The library server returned HTTP '
          '${response.statusCode}.';
    }

    if (message.length > 200) {
      message = '${message.substring(0, 200)}...';
    }

    return 'Server error ${response.statusCode}: $message';
  }

  static Future<void> _checkResponse(
    http.Response response,
    Set<int> expectedCodes,
  ) async {
    await ApiClient.handleUnauthorized(response);

    if (!expectedCodes.contains(response.statusCode)) {
      throw Exception(_extractError(response));
    }
  }

  static Future<List<dynamic>> _getList(String path, {bool refresh = false}) async {
    final uri = _uri(path);
    final headers = await _headers();
    final response = await ApiClient.offlineFirstGet(
      uri,
      headers: headers,
      forceRefresh: refresh,
    );

    await _checkResponse(response, const {200});

    dynamic decoded;

    try {
      decoded = jsonDecode(response.body);
    } on FormatException {
      throw Exception(
        'The library server returned invalid JSON for $path.',
      );
    }

    if (decoded is! List) {
      throw Exception(
        'The library server returned an unexpected response '
        'for $path. Expected a list.',
      );
    }

    return decoded;
  }

  static Future<void> _post(
    String path, {
    Map<String, dynamic>? data,
    Set<int> expectedCodes = const {200, 201},
  }) async {
    final response = await http.post(
      _uri(path),
      headers: await _headers(),
      body: data == null ? null : jsonEncode(data),
    );

    await _checkResponse(response, expectedCodes);
    ApiClient.announceSuccessfulMutation(response.request?.url ?? _uri(path));
  }

  static Future<void> _put(
    String path,
    Map<String, dynamic> data,
  ) async {
    if (data.isEmpty) {
      throw Exception('No update data was supplied.');
    }

    final response = await http.put(
      _uri(path),
      headers: await _headers(),
      body: jsonEncode(data),
    );

    await _checkResponse(response, const {200});
    ApiClient.announceSuccessfulMutation(response.request?.url ?? _uri(path));
  }

  // ============================================================
  // BOOKS DIRECTORY
  // ============================================================

  static Future<List<dynamic>> getBooks({bool refresh = false}) async {
    return _getList('books', refresh: refresh);
  }

  static Future<void> addBook(
    Map<String, dynamic> bookData,
  ) async {
    if (bookData.isEmpty) {
      throw Exception('No book data was supplied.');
    }

    await _post(
      'books',
      data: Map<String, dynamic>.from(bookData),
    );
  }

  static Future<void> updateBook(
    String bookId,
    Map<String, dynamic> bookData,
  ) async {
    final id = _pathId(bookId, 'Book ID');

    // The ID is supplied in the URL and must not be updated.
    final payload = Map<String, dynamic>.from(bookData)
      ..remove('id');

    await _put('books/$id', payload);
  }

  // ============================================================
  // BORROWING AND CIRCULATION
  // ============================================================

  static Future<List<dynamic>> getBorrowingRecords({bool refresh = false}) async {
    return _getList('borrow-records', refresh: refresh);
  }

  static Future<void> issueBook(
    Map<String, dynamic> issueData,
  ) async {
    final studentId = _requiredText(
      issueData['student_id'],
      'Student ID',
    );

    final bookId = _requiredText(
      issueData['book_id'],
      'Book ID',
    );

    final rawCampus = issueData['campus'];

    if (rawCampus is! String ||
        rawCampus.trim().isEmpty ||
        rawCampus.trim().toLowerCase() == 'null') {
      throw Exception(
        'Enter the correct issuing campus in the issuance form.',
      );
    }

    final campus = rawCampus.trim();

    final borrowDate = _requiredDate(
      issueData['borrow_date'],
      'Borrow date',
    );

    final dueDate = _requiredDate(
      issueData['due_date'],
      'Due date',
    );

    if (!dueDate.isAfter(borrowDate)) {
      throw Exception(
        'The due date must be after the borrow date.',
      );
    }

    final rawRemarks = issueData['remarks'];

    if (rawRemarks != null && rawRemarks is! String) {
      throw Exception('Remarks must be text.');
    }

    final remarks = rawRemarks is String
        ? rawRemarks.trim()
        : '';

    // Send only fields used by the supplied issuance endpoint.
    // PHP generates ref_no and sets the persisted status.
    final payload = <String, dynamic>{
      'student_id': studentId,
      'book_id': bookId,
      'borrow_date': borrowDate.toIso8601String(),
      'due_date': dueDate.toIso8601String(),
      'status': 'Borrowed',
      'remarks': remarks,
      'campus': campus,
    };

    await _post(
      'borrow-records/issue',
      data: payload,
    );
  }

  static Future<void> returnBook(String refNo) async {
    final reference = _pathId(
      refNo,
      'Borrowing reference number',
    );

    await _post(
      'borrow-records/return/$reference',
      expectedCodes: const {200},
    );
  }

  // ============================================================
  // STUDENT RECORDS
  // ============================================================

  static Future<List<dynamic>> getStudents({bool refresh = false}) async {
    return _getList('students', refresh: refresh);
  }

  static Future<void> addStudent(
    Map<String, dynamic> studentData,
  ) async {
    if (studentData.isEmpty) {
      throw Exception('No student data was supplied.');
    }

    await _post(
      'students',
      data: Map<String, dynamic>.from(studentData),
    );
  }

  static Future<List<dynamic>> getStudentHistory(
    String studentId,
  ) async {
    final id = _pathId(studentId, 'Student ID');

    return _getList('students/$id/history');
  }

  static Future<void> updateStudent(
    String studentId,
    Map<String, dynamic> studentData,
  ) async {
    final id = _pathId(studentId, 'Student ID');

    final payload = Map<String, dynamic>.from(studentData)
      ..remove('id');

    await _put('students/$id', payload);
  }
}
