import 'package:flutter/material.dart';

import 'package:pshared/api/responses/error/server.dart';
import 'package:pshared/provider/resource.dart';
import 'package:pshared/service/account.dart';
import 'package:pshared/utils/exception.dart';


class EmailVerificationProvider extends ChangeNotifier {
  Resource<bool> _resource = Resource(data: null, isLoading: false);
  String? _token;

  Resource<bool> get resource => _resource;
  bool get isLoading => _resource.isLoading;
  bool get isSuccess => _resource.data == true;
  Exception? get error => _resource.error;
  ErrorResponse? get errorResponse =>
      _resource.error is ErrorResponse ? _resource.error as ErrorResponse : null;
  int? get errorCode => errorResponse?.code;
  bool get isTokenAlreadyUsed {
    final response = errorResponse;
    if (response == null) return false;
    if (response.code != 409 || response.error != 'data_conflict') {
      return false;
    }
    return response.details.contains('verification token has already been used');
  }
  bool get canResendVerification =>
      errorCode == 400 || errorCode == 410 || errorCode == 500;

  Future<void> verify(String token) async {
    final trimmed = token.trim();
    if (trimmed.isEmpty) {
      _setResource(
        Resource(
          data: null,
          isLoading: false,
          error: Exception('Email verification token is empty.'),
        ),
      );
      return;
    }
    if (_token == trimmed && _resource.isLoading) return;
    _token = trimmed;
    _setResource(Resource(data: null, isLoading: true));
    try {
      await AccountService.verifyEmail(trimmed);
      _setResource(Resource(data: true, isLoading: false));
    } catch (e) {
      _setResource(
        Resource(data: null, isLoading: false, error: toException(e)),
      );
    }
  }

  void _setResource(Resource<bool> resource) {
    _resource = resource;
    notifyListeners();
  }
}
