// Onbrix CRM Go SDK
// Version: 1.0.0
// License: MIT
//
// Copyright (c) 2026 Onbrix
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Usage:
//
//	client := onbrix.NewClient("crm_your_api_key", "https://your-instance.onbrix.com")
//	modules, err := client.ListModules(context.Background())
//	if err != nil {
//	    log.Fatal(err)
//	}
//	for _, m := range modules {
//	    fmt.Println(m.Name)
//	}

package onbrix

import (
	"bytes"
	"context"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"math"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
)

const (
	// SDKVersion is the current version of the Onbrix Go SDK.
	SDKVersion = "1.0.0"

	// UserAgent is sent with every request to identify this SDK.
	UserAgent = "onbrix-go/" + SDKVersion

	// defaultTimeout is the default HTTP request timeout.
	defaultTimeout = 30 * time.Second

	// maxRetries is the maximum number of retry attempts for rate-limited requests.
	maxRetries = 3

	// headerAPIKey is the header name used for API key authentication.
	headerAPIKey = "X-API-Key"

	// headerRateLimitLimit is the header indicating the rate limit ceiling.
	headerRateLimitLimit = "X-RateLimit-Limit"

	// headerRateLimitRemaining is the header indicating remaining requests in the current window.
	headerRateLimitRemaining = "X-RateLimit-Remaining"

	// headerRateLimitReset is the header indicating when the rate limit resets (Unix timestamp).
	headerRateLimitReset = "X-RateLimit-Reset"
)

// --------------------------------------------------------------------------
// Error types
// --------------------------------------------------------------------------

// OnbrixError represents an error returned by the Onbrix API.
// It includes the HTTP status code, a human-readable message, and a machine-readable error code.
type OnbrixError struct {
	// StatusCode is the HTTP status code from the API response.
	StatusCode int `json:"-"`

	// Message is a human-readable description of the error.
	Message string `json:"error"`

	// Code is a machine-readable error code (e.g., "UNAUTHORIZED", "NOT_FOUND").
	Code string `json:"code"`
}

// Error implements the error interface for OnbrixError.
func (e *OnbrixError) Error() string {
	if e.Code != "" {
		return fmt.Sprintf("onbrix: %s (code=%s, status=%d)", e.Message, e.Code, e.StatusCode)
	}
	return fmt.Sprintf("onbrix: %s (status=%d)", e.Message, e.StatusCode)
}

// IsAuthError returns true if the error is an authentication error (HTTP 401).
func IsAuthError(err error) bool {
	if e, ok := err.(*OnbrixError); ok {
		return e.StatusCode == http.StatusUnauthorized
	}
	return false
}

// IsForbiddenError returns true if the error is a forbidden error (HTTP 403).
func IsForbiddenError(err error) bool {
	if e, ok := err.(*OnbrixError); ok {
		return e.StatusCode == http.StatusForbidden
	}
	return false
}

// IsNotFoundError returns true if the error is a not-found error (HTTP 404).
func IsNotFoundError(err error) bool {
	if e, ok := err.(*OnbrixError); ok {
		return e.StatusCode == http.StatusNotFound
	}
	return false
}

// IsRateLimitError returns true if the error is a rate-limit error (HTTP 429).
func IsRateLimitError(err error) bool {
	if e, ok := err.(*OnbrixError); ok {
		return e.StatusCode == http.StatusTooManyRequests
	}
	return false
}

// IsValidationError returns true if the error is a validation error (HTTP 400 or 422).
func IsValidationError(err error) bool {
	if e, ok := err.(*OnbrixError); ok {
		return e.StatusCode == http.StatusBadRequest || e.StatusCode == http.StatusUnprocessableEntity
	}
	return false
}

// --------------------------------------------------------------------------
// Data types
// --------------------------------------------------------------------------

// Module represents a CRM module (e.g., Contacts, Leads, Deals).
type Module struct {
	// ID is the unique identifier of the module.
	ID string `json:"id"`

	// Name is the display name of the module.
	Name string `json:"name"`

	// Slug is the URL-friendly identifier used in API paths.
	Slug string `json:"slug"`

	// Description is an optional description of the module.
	Description string `json:"description,omitempty"`

	// Fields contains the field definitions for this module.
	Fields []map[string]interface{} `json:"fields,omitempty"`

	// CreatedAt is the timestamp when the module was created.
	CreatedAt string `json:"created_at,omitempty"`

	// UpdatedAt is the timestamp when the module was last updated.
	UpdatedAt string `json:"updated_at,omitempty"`
}

// Record represents a single record within a module.
type Record struct {
	// ID is the unique identifier of the record.
	ID string `json:"id"`

	// Data contains the field values of the record as key-value pairs.
	Data map[string]interface{} `json:"data"`

	// CreatedBy is the user ID of the record creator.
	CreatedBy string `json:"created_by,omitempty"`

	// UpdatedBy is the user ID of the last person to update the record.
	UpdatedBy string `json:"updated_by,omitempty"`

	// CreatedAt is the timestamp when the record was created.
	CreatedAt string `json:"created_at,omitempty"`

	// UpdatedAt is the timestamp when the record was last updated.
	UpdatedAt string `json:"updated_at,omitempty"`
}

// Meta contains pagination metadata for list responses.
type Meta struct {
	// Total is the total number of records matching the query.
	Total int `json:"total"`

	// Page is the current page number (1-based).
	Page int `json:"page"`

	// PageSize is the number of records per page.
	PageSize int `json:"page_size"`

	// TotalPages is the total number of pages available.
	TotalPages int `json:"total_pages"`
}

// ListResponse contains a paginated list of records with metadata.
type ListResponse struct {
	// Data is the list of records on the current page.
	Data []Record `json:"data"`

	// Meta contains the pagination information.
	Meta Meta `json:"meta"`
}

// DeleteResponse contains the result of a delete operation.
type DeleteResponse struct {
	// ID is the identifier of the deleted record.
	ID string `json:"id"`

	// Deleted is true if the record was successfully deleted.
	Deleted bool `json:"deleted"`
}

// ListOptions configures filtering, sorting, and pagination for list requests.
type ListOptions struct {
	// Page is the page number to retrieve (1-based). Defaults to 1.
	Page int

	// PageSize is the number of records per page. Defaults to the API default (typically 20).
	PageSize int

	// SortBy is the field name to sort by.
	SortBy string

	// SortDir is the sort direction: "asc" or "desc".
	SortDir string

	// Search is a full-text search query applied across searchable fields.
	Search string

	// Filters is a map of field names to filter values. Each entry produces a filter[field]=value query parameter.
	Filters map[string]string
}

// --------------------------------------------------------------------------
// Client
// --------------------------------------------------------------------------

// Client is the Onbrix API client. It provides methods for interacting with
// modules and records in the CRM.
//
// Create a new client using NewClient:
//
//	client := onbrix.NewClient("crm_your_api_key", "https://your-instance.onbrix.com")
type Client struct {
	apiKey     string
	baseURL    string
	httpClient *http.Client
}

// NewClient creates a new Onbrix API client.
//
// apiKey is the API key for authentication (must start with "crm_").
// baseUrl is the base URL of the Onbrix instance (e.g., "https://your-instance.onbrix.com").
// Trailing slashes on baseUrl are automatically removed.
func NewClient(apiKey, baseUrl string) *Client {
	return &Client{
		apiKey:  apiKey,
		baseURL: strings.TrimRight(baseUrl, "/"),
		httpClient: &http.Client{
			Timeout: defaultTimeout,
		},
	}
}

// --------------------------------------------------------------------------
// Internal helpers
// --------------------------------------------------------------------------

// buildURL constructs the full API URL for a given path.
func (c *Client) buildURL(path string) string {
	return c.baseURL + "/api/v1" + path
}

// doRequest executes an HTTP request with authentication, context awareness,
// and automatic retry on rate limiting (HTTP 429).
func (c *Client) doRequest(ctx context.Context, method, url string, body interface{}) ([]byte, error) {
	var attempt int

	for {
		var reqBody io.Reader
		if body != nil {
			jsonBytes, err := json.Marshal(body)
			if err != nil {
				return nil, fmt.Errorf("onbrix: failed to marshal request body: %w", err)
			}
			reqBody = bytes.NewReader(jsonBytes)
		}

		req, err := http.NewRequestWithContext(ctx, method, url, reqBody)
		if err != nil {
			return nil, fmt.Errorf("onbrix: failed to create request: %w", err)
		}

		req.Header.Set(headerAPIKey, c.apiKey)
		req.Header.Set("User-Agent", UserAgent)
		req.Header.Set("Accept", "application/json")
		if body != nil {
			req.Header.Set("Content-Type", "application/json")
		}

		resp, err := c.httpClient.Do(req)
		if err != nil {
			return nil, fmt.Errorf("onbrix: request failed: %w", err)
		}

		respBody, err := io.ReadAll(resp.Body)
		resp.Body.Close()
		if err != nil {
			return nil, fmt.Errorf("onbrix: failed to read response body: %w", err)
		}

		// Handle rate limiting with automatic retry
		if resp.StatusCode == http.StatusTooManyRequests && attempt < maxRetries {
			attempt++
			sleepDuration := calculateBackoff(resp, attempt)

			select {
			case <-ctx.Done():
				return nil, ctx.Err()
			case <-time.After(sleepDuration):
				continue
			}
		}

		// Handle error responses
		if resp.StatusCode >= 400 {
			apiErr := &OnbrixError{StatusCode: resp.StatusCode}
			if jsonErr := json.Unmarshal(respBody, apiErr); jsonErr != nil {
				apiErr.Message = fmt.Sprintf("HTTP %d: %s", resp.StatusCode, http.StatusText(resp.StatusCode))
			}
			return nil, apiErr
		}

		return respBody, nil
	}
}

// calculateBackoff determines how long to wait before retrying a rate-limited request.
// It first checks the X-RateLimit-Reset header; if unavailable, it uses exponential backoff.
func calculateBackoff(resp *http.Response, attempt int) time.Duration {
	if resetStr := resp.Header.Get(headerRateLimitReset); resetStr != "" {
		if resetUnix, err := strconv.ParseInt(resetStr, 10, 64); err == nil {
			resetTime := time.Unix(resetUnix, 0)
			wait := time.Until(resetTime)
			if wait > 0 {
				return wait
			}
		}
	}
	// Exponential backoff: 1s, 2s, 4s, ...
	return time.Duration(math.Pow(2, float64(attempt-1))) * time.Second
}

// --------------------------------------------------------------------------
// Module operations
// --------------------------------------------------------------------------

// ListModules retrieves all modules available to the authenticated user.
//
// Example:
//
//	modules, err := client.ListModules(ctx)
//	if err != nil {
//	    log.Fatal(err)
//	}
//	for _, m := range modules {
//	    fmt.Printf("Module: %s (%s)\n", m.Name, m.Slug)
//	}
func (c *Client) ListModules(ctx context.Context) ([]Module, error) {
	respBody, err := c.doRequest(ctx, http.MethodGet, c.buildURL("/modules"), nil)
	if err != nil {
		return nil, err
	}

	var result struct {
		Data []Module `json:"data"`
	}
	if err := json.Unmarshal(respBody, &result); err != nil {
		return nil, fmt.Errorf("onbrix: failed to parse modules response: %w", err)
	}
	return result.Data, nil
}

// --------------------------------------------------------------------------
// Record operations
// --------------------------------------------------------------------------

// ListRecords retrieves a paginated list of records from the specified module.
// Pass nil for opts to use default pagination and sorting.
//
// Example:
//
//	resp, err := client.ListRecords(ctx, "contacts", &onbrix.ListOptions{
//	    Page:     1,
//	    PageSize: 50,
//	    SortBy:   "created_at",
//	    SortDir:  "desc",
//	    Search:   "acme",
//	    Filters:  map[string]string{"status": "active"},
//	})
func (c *Client) ListRecords(ctx context.Context, moduleSlug string, opts *ListOptions) (*ListResponse, error) {
	endpoint := c.buildURL("/" + url.PathEscape(moduleSlug))

	if opts != nil {
		params := url.Values{}
		if opts.Page > 0 {
			params.Set("page", strconv.Itoa(opts.Page))
		}
		if opts.PageSize > 0 {
			params.Set("page_size", strconv.Itoa(opts.PageSize))
		}
		if opts.SortBy != "" {
			params.Set("sort_by", opts.SortBy)
		}
		if opts.SortDir != "" {
			params.Set("sort_dir", opts.SortDir)
		}
		if opts.Search != "" {
			params.Set("search", opts.Search)
		}
		for field, value := range opts.Filters {
			params.Set("filter["+field+"]", value)
		}
		if encoded := params.Encode(); encoded != "" {
			endpoint += "?" + encoded
		}
	}

	respBody, err := c.doRequest(ctx, http.MethodGet, endpoint, nil)
	if err != nil {
		return nil, err
	}

	var result ListResponse
	if err := json.Unmarshal(respBody, &result); err != nil {
		return nil, fmt.Errorf("onbrix: failed to parse list response: %w", err)
	}
	return &result, nil
}

// GetRecord retrieves a single record by its ID from the specified module.
//
// Example:
//
//	record, err := client.GetRecord(ctx, "contacts", "abc-123")
//	if err != nil {
//	    if onbrix.IsNotFoundError(err) {
//	        fmt.Println("Contact not found")
//	    }
//	}
func (c *Client) GetRecord(ctx context.Context, moduleSlug, recordId string) (*Record, error) {
	endpoint := c.buildURL("/" + url.PathEscape(moduleSlug) + "/" + url.PathEscape(recordId))

	respBody, err := c.doRequest(ctx, http.MethodGet, endpoint, nil)
	if err != nil {
		return nil, err
	}

	var result struct {
		Data Record `json:"data"`
	}
	if err := json.Unmarshal(respBody, &result); err != nil {
		return nil, fmt.Errorf("onbrix: failed to parse record response: %w", err)
	}
	return &result.Data, nil
}

// CreateRecord creates a new record in the specified module.
// The data map should contain field names as keys and their values.
//
// Example:
//
//	record, err := client.CreateRecord(ctx, "contacts", map[string]interface{}{
//	    "first_name": "John",
//	    "last_name":  "Doe",
//	    "email":      "john@example.com",
//	})
func (c *Client) CreateRecord(ctx context.Context, moduleSlug string, data map[string]interface{}) (*Record, error) {
	endpoint := c.buildURL("/" + url.PathEscape(moduleSlug))

	body := map[string]interface{}{
		"data": data,
	}

	respBody, err := c.doRequest(ctx, http.MethodPost, endpoint, body)
	if err != nil {
		return nil, err
	}

	var result struct {
		Data Record `json:"data"`
	}
	if err := json.Unmarshal(respBody, &result); err != nil {
		return nil, fmt.Errorf("onbrix: failed to parse create response: %w", err)
	}
	return &result.Data, nil
}

// UpdateRecord updates an existing record in the specified module.
// The data map should contain only the fields to be updated.
//
// Example:
//
//	record, err := client.UpdateRecord(ctx, "contacts", "abc-123", map[string]interface{}{
//	    "email": "new-email@example.com",
//	})
func (c *Client) UpdateRecord(ctx context.Context, moduleSlug, recordId string, data map[string]interface{}) (*Record, error) {
	endpoint := c.buildURL("/" + url.PathEscape(moduleSlug) + "/" + url.PathEscape(recordId))

	body := map[string]interface{}{
		"data": data,
	}

	respBody, err := c.doRequest(ctx, http.MethodPut, endpoint, body)
	if err != nil {
		return nil, err
	}

	var result struct {
		Data Record `json:"data"`
	}
	if err := json.Unmarshal(respBody, &result); err != nil {
		return nil, fmt.Errorf("onbrix: failed to parse update response: %w", err)
	}
	return &result.Data, nil
}

// DeleteRecord deletes a record by its ID from the specified module.
//
// Example:
//
//	resp, err := client.DeleteRecord(ctx, "contacts", "abc-123")
//	if err != nil {
//	    log.Fatal(err)
//	}
//	if resp.Deleted {
//	    fmt.Println("Record deleted successfully")
//	}
func (c *Client) DeleteRecord(ctx context.Context, moduleSlug, recordId string) (*DeleteResponse, error) {
	endpoint := c.buildURL("/" + url.PathEscape(moduleSlug) + "/" + url.PathEscape(recordId))

	respBody, err := c.doRequest(ctx, http.MethodDelete, endpoint, nil)
	if err != nil {
		return nil, err
	}

	var result struct {
		Data DeleteResponse `json:"data"`
	}
	if err := json.Unmarshal(respBody, &result); err != nil {
		return nil, fmt.Errorf("onbrix: failed to parse delete response: %w", err)
	}
	return &result.Data, nil
}

// --------------------------------------------------------------------------
// Webhook verification
// --------------------------------------------------------------------------

// VerifyWebhookSignature verifies the HMAC-SHA256 signature of an incoming webhook payload.
// The signature should be in the format "sha256={hex_digest}" as received in the
// X-Webhook-Signature header. The secret is the webhook endpoint's signing secret.
//
// Returns true if the signature is valid, false otherwise.
//
// Example:
//
//	body, _ := io.ReadAll(r.Body)
//	sig := r.Header.Get("X-Webhook-Signature")
//	if !onbrix.VerifyWebhookSignature(body, sig, "your_webhook_secret") {
//	    http.Error(w, "Invalid signature", http.StatusUnauthorized)
//	    return
//	}
func VerifyWebhookSignature(payload []byte, signature, secret string) bool {
	if !strings.HasPrefix(signature, "sha256=") {
		return false
	}

	receivedHex := strings.TrimPrefix(signature, "sha256=")
	receivedBytes, err := hex.DecodeString(receivedHex)
	if err != nil {
		return false
	}

	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write(payload)
	expectedBytes := mac.Sum(nil)

	return hmac.Equal(receivedBytes, expectedBytes)
}
