package keybase

import (
	"context"
	"fmt"
)

type NewVerificationMethodInput struct {
	MethodID   string `json:"method_id"`
	MethodType string `json:"method_type"`
	Controller string `json:"controller"`
	PublicKey  string `json:"public_key"`
	Purpose    string `json:"purpose"`
}

func (am *ActionManager) CreateVerificationMethod(ctx context.Context, params NewVerificationMethodInput) (*VerificationMethodResult, error) {
	am.kb.mu.Lock()
	defer am.kb.mu.Unlock()

	if am.kb.didID == 0 {
		return nil, fmt.Errorf("DID not initialized")
	}

	vm, err := am.kb.queries.CreateVerificationMethod(ctx, CreateVerificationMethodParams{
		DidID:      am.kb.didID,
		MethodID:   params.MethodID,
		MethodType: params.MethodType,
		Controller: params.Controller,
		PublicKey:  params.PublicKey,
		Purpose:    params.Purpose,
	})
	if err != nil {
		return nil, fmt.Errorf("create verification method: %w", err)
	}

	return &VerificationMethodResult{
		ID:         vm.MethodID,
		Type:       vm.MethodType,
		Controller: vm.Controller,
		PublicKey:  vm.PublicKey,
		Purpose:    vm.Purpose,
	}, nil
}

func (am *ActionManager) ListVerificationMethodsFull(ctx context.Context) ([]VerificationMethodResult, error) {
	am.kb.mu.RLock()
	defer am.kb.mu.RUnlock()

	if am.kb.didID == 0 {
		return []VerificationMethodResult{}, nil
	}

	vms, err := am.kb.queries.ListVerificationMethods(ctx, am.kb.didID)
	if err != nil {
		return nil, fmt.Errorf("list verification methods: %w", err)
	}

	results := make([]VerificationMethodResult, len(vms))
	for i, vm := range vms {
		results[i] = VerificationMethodResult{
			ID:         vm.MethodID,
			Type:       vm.MethodType,
			Controller: vm.Controller,
			PublicKey:  vm.PublicKey,
			Purpose:    vm.Purpose,
		}
	}

	return results, nil
}

func (am *ActionManager) GetVerificationMethod(ctx context.Context, methodID string) (*VerificationMethodResult, error) {
	am.kb.mu.RLock()
	defer am.kb.mu.RUnlock()

	if am.kb.didID == 0 {
		return nil, fmt.Errorf("DID not initialized")
	}

	vm, err := am.kb.queries.GetVerificationMethod(ctx, GetVerificationMethodParams{
		DidID:    am.kb.didID,
		MethodID: methodID,
	})
	if err != nil {
		return nil, fmt.Errorf("get verification method: %w", err)
	}

	return &VerificationMethodResult{
		ID:         vm.MethodID,
		Type:       vm.MethodType,
		Controller: vm.Controller,
		PublicKey:  vm.PublicKey,
		Purpose:    vm.Purpose,
	}, nil
}

func (am *ActionManager) DeleteVerificationMethod(ctx context.Context, methodID string) error {
	am.kb.mu.Lock()
	defer am.kb.mu.Unlock()

	if am.kb.didID == 0 {
		return fmt.Errorf("DID not initialized")
	}

	vm, err := am.kb.queries.GetVerificationMethod(ctx, GetVerificationMethodParams{
		DidID:    am.kb.didID,
		MethodID: methodID,
	})
	if err != nil {
		return fmt.Errorf("get verification method: %w", err)
	}

	return am.kb.queries.DeleteVerificationMethod(ctx, vm.ID)
}
