//go:build dev

package square

import (
	"context"
	"crussell/clock"
	"fmt"
	"log"
	"os"
	"sync"
	"time"
)

var Client SquareClient

var isTesting = os.Getenv("GO_TESTING") == "1"

func mockSleep(d time.Duration) {
	if !isTesting {
		time.Sleep(d)
	}
}

type MockClient struct {
	mu        sync.RWMutex
	cards     map[string]map[string]*CardOnFile
	checkouts map[string]*CheckoutResult
	payments  map[string]*PaymentResult
	refunds   map[string]*RefundResult
	completed map[string]*PaymentResult
}

type devProdClient struct{}

func (d *devProdClient) CreatePayment(ctx context.Context, req CreatePaymentReq) (*PaymentResult, error) {
	return nil, fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (d *devProdClient) CreateCheckout(ctx context.Context, req CreateCheckoutReq) (*CheckoutResult, error) {
	return nil, fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (d *devProdClient) GetCheckout(ctx context.Context, checkoutID string) (*PaymentResult, error) {
	return nil, fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (d *devProdClient) RefundPayment(ctx context.Context, req RefundPaymentReq) (*RefundResult, error) {
	return nil, fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (d *devProdClient) CreateCardOnFile(ctx context.Context, userID, cardToken string) (*CardOnFile, error) {
	return nil, fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (d *devProdClient) CreateCardOnFileRaw(ctx context.Context, userID, cardNumber string, expMonth, expYear int, cvc string) (*CardOnFile, error) {
	return nil, fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (d *devProdClient) GetCardsOnFile(ctx context.Context, userID string) ([]CardOnFile, error) {
	return nil, fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (d *devProdClient) DeleteCardOnFile(ctx context.Context, cardID string) error {
	return fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}

func NewClient() SquareClient {
	return NewDevClient()
}

func NewDevClient() SquareClient {
	env := os.Getenv("SQUARE_ENVIRONMENT")
	if env == "sandbox" || env == "production" {
		log.Printf("[SQUARE-MOCK] SQUARE_ENVIRONMENT=%s — real client TODO stub", env)
		return &devProdClient{}
	}
	log.Println("[SQUARE-MOCK] Using in-memory mock client")
	return &MockClient{
		cards:     make(map[string]map[string]*CardOnFile),
		checkouts: make(map[string]*CheckoutResult),
		payments:  make(map[string]*PaymentResult),
		refunds:   make(map[string]*RefundResult),
		completed: make(map[string]*PaymentResult),
	}
}

func (m *MockClient) CreatePayment(ctx context.Context, req CreatePaymentReq) (*PaymentResult, error) {
	log.Printf("[SQUARE-MOCK] CreatePayment: amount=%d, reference=%s", req.Amount, req.ReferenceID)
	mockSleep(1 * time.Second)

	m.mu.Lock()
	defer m.mu.Unlock()

	paymentID := fmt.Sprintf("pay_mock_%d", clock.Now().UnixNano())
	fees := req.Amount*14/1000 + 25 // online rate: 1.4% + 25p

	result := &PaymentResult{
		ID:          paymentID,
		Status:      "COMPLETED",
		Amount:      req.Amount,
		CardBrand:   "VISA",
		CardLast4:   "4242",
		TipAmount:   0,
		ReceiptURL:  "https://squareup.com/receipt/" + paymentID,
		SquarePayID: "sqp_" + paymentID,
		Fees:        fees,
	}
	m.payments[paymentID] = result
	log.Printf("[SQUARE-MOCK] Payment completed: id=%s, fees=%d", paymentID, fees)
	return result, nil
}

func (m *MockClient) CreateCheckout(ctx context.Context, req CreateCheckoutReq) (*CheckoutResult, error) {
	log.Printf("[SQUARE-MOCK] CreateCheckout: amount=%d, tipEnabled=%v, reference=%s", req.Amount, req.TipEnabled, req.ReferenceID)

	checkoutID := fmt.Sprintf("chk_mock_%d", clock.Now().UnixNano())
	result := &CheckoutResult{
		ID:     checkoutID,
		Status: "PENDING",
	}

	m.mu.Lock()
	m.checkouts[checkoutID] = result
	m.mu.Unlock()

	go func() {
		defer func() {
			if r := recover(); r != nil {
				log.Printf("Panic recovered in Square mock payment processing: %v", r)
			}
		}()
		mockSleep(3 * time.Second)

		m.mu.Lock()
		defer m.mu.Unlock()

		paymentID := fmt.Sprintf("pay_%d", clock.Now().UnixNano())
		amount := req.Amount
		tipAmount := int64(0)
		if req.TipEnabled {
			tipAmount = 500
			amount += tipAmount
		}
		fees := amount * 175 / 10000 // in-person rate: 1.75%

		paymentResult := &PaymentResult{
			ID:          paymentID,
			Status:      "COMPLETED",
			Amount:      amount,
			CardBrand:   "VISA",
			CardLast4:   "4242",
			TipAmount:   tipAmount,
			ReceiptURL:  "https://squareup.com/receipt/" + paymentID,
			SquarePayID: "sqp_" + paymentID,
			Fees:        fees,
		}
		m.completed[checkoutID] = paymentResult
		m.checkouts[checkoutID].Status = "COMPLETED"
		log.Printf("[SQUARE-MOCK] Checkout completed: id=%s, amount=%d, tip=%d", checkoutID, amount, tipAmount)
	}()

	return result, nil
}

func (m *MockClient) GetCheckout(ctx context.Context, checkoutID string) (*PaymentResult, error) {
	log.Printf("[SQUARE-MOCK] GetCheckout: id=%s", checkoutID)

	m.mu.RLock()
	defer m.mu.RUnlock()

	checkout, ok := m.checkouts[checkoutID]
	if !ok {
		return nil, fmt.Errorf("checkout not found: %s", checkoutID)
	}

	if checkout.Status == "PENDING" {
		return nil, fmt.Errorf("checkout pending")
	}

	result, ok := m.completed[checkoutID]
	if !ok {
		return nil, fmt.Errorf("checkout result not found: %s", checkoutID)
	}

	return result, nil
}

func (m *MockClient) RefundPayment(ctx context.Context, req RefundPaymentReq) (*RefundResult, error) {
	log.Printf("[SQUARE-MOCK] RefundPayment: payment=%s, amount=%d", req.PaymentID, req.Amount)
	mockSleep(1 * time.Second)

	m.mu.Lock()
	defer m.mu.Unlock()

	refundID := fmt.Sprintf("ref_mock_%d", clock.Now().UnixNano())
	amount := req.Amount
	if amount == 0 {
		if payment, ok := m.payments[req.PaymentID]; ok {
			amount = payment.Amount
		}
	}

	result := &RefundResult{
		ID:     refundID,
		Status: "COMPLETED",
		Amount: amount,
	}
	m.refunds[refundID] = result
	log.Printf("[SQUARE-MOCK] Refund completed: id=%s, amount=%d", refundID, amount)
	return result, nil
}

func (m *MockClient) CreateCardOnFile(ctx context.Context, userID, cardToken string) (*CardOnFile, error) {
	log.Printf("[SQUARE-MOCK] CreateCardOnFile: user=%s", userID)

	m.mu.Lock()
	defer m.mu.Unlock()

	if m.cards[userID] == nil {
		m.cards[userID] = make(map[string]*CardOnFile)
	}

	cardID := fmt.Sprintf("mock_card_%d", clock.Now().UnixNano())
	card := &CardOnFile{
		ID:          cardID,
		CardID:      "cfa_" + cardID,
		Brand:       "VISA",
		Last4:       "4242",
		ExpMonth:    12,
		ExpYear:     2030,
		Fingerprint: fmt.Sprintf("fp_%d", clock.Now().UnixNano()),
		IsDefault:   len(m.cards[userID]) == 0,
	}
	m.cards[userID][cardID] = card
	log.Printf("[SQUARE-MOCK] Card created: id=%s, brand=%s, last4=%s", cardID, card.Brand, card.Last4)
	return card, nil
}

func (m *MockClient) CreateCardOnFileRaw(ctx context.Context, userID, cardNumber string, expMonth, expYear int, cvc string) (*CardOnFile, error) {
	log.Printf("[SQUARE-MOCK] CreateCardOnFileRaw: user=%s", userID)

	m.mu.Lock()
	defer m.mu.Unlock()

	if m.cards[userID] == nil {
		m.cards[userID] = make(map[string]*CardOnFile)
	}

	cardID := fmt.Sprintf("mock_card_%d", clock.Now().UnixNano())
	last4 := cardNumber[len(cardNumber)-4:]
	brands := map[string]string{"4": "VISA", "5": "MASTERCARD", "3": "AMEX", "6": "DISCOVER"}
	brand := brands[string(cardNumber[0])]
	if brand == "" {
		brand = "VISA"
	}

	card := &CardOnFile{
		ID:          cardID,
		CardID:      "cfa_" + cardID,
		Brand:       brand,
		Last4:       last4,
		ExpMonth:    expMonth,
		ExpYear:     expYear,
		Fingerprint: fmt.Sprintf("fp_%d", clock.Now().UnixNano()),
		IsDefault:   len(m.cards[userID]) == 0,
	}
	m.cards[userID][cardID] = card
	log.Printf("[SQUARE-MOCK] Card created: id=%s, brand=%s, last4=%s", cardID, card.Brand, card.Last4)
	return card, nil
}

func (m *MockClient) GetCardsOnFile(ctx context.Context, userID string) ([]CardOnFile, error) {
	log.Printf("[SQUARE-MOCK] GetCardsOnFile: user=%s", userID)

	m.mu.RLock()
	defer m.mu.RUnlock()

	userCards, ok := m.cards[userID]
	if !ok {
		return []CardOnFile{}, nil
	}

	var cards []CardOnFile
	for _, card := range userCards {
		cards = append(cards, *card)
	}
	return cards, nil
}

func (m *MockClient) DeleteCardOnFile(ctx context.Context, cardID string) error {
	log.Printf("[SQUARE-MOCK] DeleteCardOnFile: id=%s", cardID)

	m.mu.Lock()
	defer m.mu.Unlock()

	for userID, cards := range m.cards {
		if _, ok := cards[cardID]; ok {
			delete(m.cards[userID], cardID)
			log.Printf("[SQUARE-MOCK] Card deleted: id=%s (user=%s)", cardID, userID)
			return nil
		}
	}
	return fmt.Errorf("card not found: %s", cardID)
}
