package businessapi

import "encoding/json"

// SendMessageRequest represents a request to send a message via Business API
type SendMessageRequest struct {
	MessagingProduct string                 `json:"messaging_product"`        // Always "whatsapp"
	RecipientType    string                 `json:"recipient_type,omitempty"` // "individual"
	To               string                 `json:"to"`                       // Phone number in E.164 format
	Type             string                 `json:"type"`                     // "text", "image", "video", "document", "audio", "sticker", "location", "contacts", "interactive", "template"
	Text             *TextObject            `json:"text,omitempty"`
	Image            *MediaObject           `json:"image,omitempty"`
	Video            *MediaObject           `json:"video,omitempty"`
	Document         *DocumentObject        `json:"document,omitempty"`
	Audio            *MediaObject           `json:"audio,omitempty"`
	Sticker          *MediaObject           `json:"sticker,omitempty"`
	Location         *LocationObject        `json:"location,omitempty"`
	Contacts         []SendContactObject    `json:"contacts,omitempty"`
	Interactive      *InteractiveObject     `json:"interactive,omitempty"`
	Template         *TemplateMessageObject `json:"template,omitempty"`
}

// TextObject represents a text message
type TextObject struct {
	Body string `json:"body"`
}

// MediaObject represents media (image/video) message
type MediaObject struct {
	ID      string `json:"id,omitempty"`   // Media ID (from upload)
	Link    string `json:"link,omitempty"` // Or direct URL
	Caption string `json:"caption,omitempty"`
}

// DocumentObject represents a document message
type DocumentObject struct {
	ID       string `json:"id,omitempty"`   // Media ID (from upload)
	Link     string `json:"link,omitempty"` // Or direct URL
	Caption  string `json:"caption,omitempty"`
	Filename string `json:"filename,omitempty"`
}

// SendMessageResponse represents the response from sending a message
type SendMessageResponse struct {
	MessagingProduct string `json:"messaging_product"`
	Contacts         []struct {
		Input string `json:"input"`
		WaID  string `json:"wa_id"`
	} `json:"contacts"`
	Messages []struct {
		ID string `json:"id"`
	} `json:"messages"`
}

// MediaUploadResponse represents the response from uploading media
type MediaUploadResponse struct {
	ID string `json:"id"` // Media ID to use in messages
}

// MediaURLResponse represents the response when getting media URL
type MediaURLResponse struct {
	URL              string `json:"url"` // CDN URL to download media
	MimeType         string `json:"mime_type"`
	SHA256           string `json:"sha256"`
	FileSize         int64  `json:"file_size"`
	ID               string `json:"id"`
	MessagingProduct string `json:"messaging_product"`
}

// ErrorResponse represents an error from the Business API
type ErrorResponse struct {
	Error struct {
		Message      string `json:"message"`
		Type         string `json:"type"`
		Code         int    `json:"code"`
		ErrorSubcode int    `json:"error_subcode,omitempty"`
		FBTraceID    string `json:"fbtrace_id,omitempty"`
	} `json:"error"`
}

// WebhookPayload represents the incoming webhook from WhatsApp Business API
type WebhookPayload struct {
	Object string         `json:"object"` // "whatsapp_business_account"
	Entry  []WebhookEntry `json:"entry"`
}

// WebhookEntry represents an entry in the webhook
type WebhookEntry struct {
	ID      string          `json:"id"` // WhatsApp Business Account ID
	Changes []WebhookChange `json:"changes"`
}

// WebhookChange represents a change notification.
// Value is kept as raw JSON because the shape differs per Field type:
// "messages" → WebhookValue, "message_template_status_update" → TemplateStatusValue, etc.
type WebhookChange struct {
	Value json.RawMessage `json:"value"`
	Field string          `json:"field"`
}

// WebhookValue contains the actual webhook data
type WebhookValue struct {
	MessagingProduct string           `json:"messaging_product"`
	Metadata         WebhookMetadata  `json:"metadata"`
	Contacts         []WebhookContact `json:"contacts,omitempty"`
	Messages         []WebhookMessage `json:"messages,omitempty"`
	Statuses         []WebhookStatus  `json:"statuses,omitempty"`
}

// WebhookMetadata contains metadata about the phone number
type WebhookMetadata struct {
	DisplayPhoneNumber string `json:"display_phone_number"`
	PhoneNumberID      string `json:"phone_number_id"`
}

// WebhookContact represents a contact in the webhook
type WebhookContact struct {
	Profile WebhookProfile `json:"profile"`
	WaID    string         `json:"wa_id"`
}

// WebhookProfile contains profile information
type WebhookProfile struct {
	Name string `json:"name"`
}

// WebhookMessage represents a message in the webhook
type WebhookMessage struct {
	From        string                  `json:"from"`      // Sender phone number
	ID          string                  `json:"id"`        // Message ID
	Timestamp   string                  `json:"timestamp"` // Unix timestamp as string
	Type        string                  `json:"type"`      // "text", "image", "video", "document", "audio", "sticker", "location", "contacts", "interactive", "button", "order", "system", "unknown", "reaction"
	Text        *WebhookText            `json:"text,omitempty"`
	Image       *WebhookMediaMessage    `json:"image,omitempty"`
	Video       *WebhookMediaMessage    `json:"video,omitempty"`
	Document    *WebhookDocumentMessage `json:"document,omitempty"`
	Audio       *WebhookMediaMessage    `json:"audio,omitempty"`
	Sticker     *WebhookMediaMessage    `json:"sticker,omitempty"`
	Location    *WebhookLocation        `json:"location,omitempty"`
	Contacts    []WebhookContactCard    `json:"contacts,omitempty"`
	Interactive *WebhookInteractive     `json:"interactive,omitempty"`
	Button      *WebhookButton          `json:"button,omitempty"`
	Reaction    *WebhookReaction        `json:"reaction,omitempty"`
	Order       *WebhookOrder           `json:"order,omitempty"`
	System      *WebhookSystem          `json:"system,omitempty"`
	Context     *WebhookContext         `json:"context,omitempty"` // Reply context
	Identity    *WebhookIdentity        `json:"identity,omitempty"`
	Referral    *WebhookReferral        `json:"referral,omitempty"`
}

// WebhookText represents a text message
type WebhookText struct {
	Body string `json:"body"`
}

// WebhookMediaMessage represents a media message (image/video)
type WebhookMediaMessage struct {
	ID       string `json:"id"` // Media ID
	MimeType string `json:"mime_type"`
	SHA256   string `json:"sha256"`
	Caption  string `json:"caption,omitempty"`
}

// WebhookDocumentMessage represents a document message
type WebhookDocumentMessage struct {
	ID       string `json:"id"` // Media ID
	MimeType string `json:"mime_type"`
	SHA256   string `json:"sha256"`
	Filename string `json:"filename,omitempty"`
	Caption  string `json:"caption,omitempty"`
}

// WebhookContext represents reply context
type WebhookContext struct {
	From      string `json:"from"`
	ID        string `json:"id"` // Message ID being replied to
	MessageID string `json:"message_id,omitempty"`
}

// WebhookLocation represents a location message
type WebhookLocation struct {
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
	Name      string  `json:"name,omitempty"`
	Address   string  `json:"address,omitempty"`
}

// WebhookContactCard represents a contact card
type WebhookContactCard struct {
	Addresses []WebhookContactAddress `json:"addresses,omitempty"`
	Birthday  string                  `json:"birthday,omitempty"`
	Emails    []WebhookContactEmail   `json:"emails,omitempty"`
	Name      WebhookContactName      `json:"name"`
	Org       WebhookContactOrg       `json:"org,omitempty"`
	Phones    []WebhookContactPhone   `json:"phones,omitempty"`
	URLs      []WebhookContactURL     `json:"urls,omitempty"`
}

// WebhookContactAddress represents a contact address
type WebhookContactAddress struct {
	City        string `json:"city,omitempty"`
	Country     string `json:"country,omitempty"`
	CountryCode string `json:"country_code,omitempty"`
	State       string `json:"state,omitempty"`
	Street      string `json:"street,omitempty"`
	Type        string `json:"type,omitempty"`
	Zip         string `json:"zip,omitempty"`
}

// WebhookContactEmail represents a contact email
type WebhookContactEmail struct {
	Email string `json:"email,omitempty"`
	Type  string `json:"type,omitempty"`
}

// WebhookContactName represents a contact name
type WebhookContactName struct {
	FormattedName string `json:"formatted_name"`
	FirstName     string `json:"first_name,omitempty"`
	LastName      string `json:"last_name,omitempty"`
	MiddleName    string `json:"middle_name,omitempty"`
	Suffix        string `json:"suffix,omitempty"`
	Prefix        string `json:"prefix,omitempty"`
}

// WebhookContactOrg represents a contact organization
type WebhookContactOrg struct {
	Company    string `json:"company,omitempty"`
	Department string `json:"department,omitempty"`
	Title      string `json:"title,omitempty"`
}

// WebhookContactPhone represents a contact phone
type WebhookContactPhone struct {
	Phone string `json:"phone,omitempty"`
	Type  string `json:"type,omitempty"`
	WaID  string `json:"wa_id,omitempty"`
}

// WebhookContactURL represents a contact URL
type WebhookContactURL struct {
	URL  string `json:"url,omitempty"`
	Type string `json:"type,omitempty"`
}

// WebhookInteractive represents an interactive message response
type WebhookInteractive struct {
	Type        string              `json:"type"` // "button_reply", "list_reply"
	ButtonReply *WebhookButtonReply `json:"button_reply,omitempty"`
	ListReply   *WebhookListReply   `json:"list_reply,omitempty"`
	NfmReply    *WebhookNfmReply    `json:"nfm_reply,omitempty"`
}

// WebhookButtonReply represents a button reply
type WebhookButtonReply struct {
	ID    string `json:"id"`
	Title string `json:"title"`
}

// WebhookListReply represents a list reply
type WebhookListReply struct {
	ID          string `json:"id"`
	Title       string `json:"title"`
	Description string `json:"description,omitempty"`
}

// WebhookNfmReply represents a native flow message reply
type WebhookNfmReply struct {
	ResponseJSON string `json:"response_json"`
	Body         string `json:"body"`
	Name         string `json:"name"`
}

// WebhookButton represents a quick reply button
type WebhookButton struct {
	Text    string `json:"text"`
	Payload string `json:"payload"`
}

// WebhookReaction represents a reaction to a message
type WebhookReaction struct {
	MessageID string `json:"message_id"`
	Emoji     string `json:"emoji"`
}

// WebhookOrder represents an order
type WebhookOrder struct {
	CatalogID    string               `json:"catalog_id"`
	ProductItems []WebhookProductItem `json:"product_items"`
	Text         string               `json:"text,omitempty"`
}

// WebhookProductItem represents a product in an order
type WebhookProductItem struct {
	ProductRetailerID string  `json:"product_retailer_id"`
	Quantity          int     `json:"quantity"`
	ItemPrice         float64 `json:"item_price"`
	Currency          string  `json:"currency"`
}

// WebhookSystem represents a system message
type WebhookSystem struct {
	Body     string `json:"body,omitempty"`
	Type     string `json:"type,omitempty"` // "customer_changed_number", "customer_identity_changed", etc.
	Identity string `json:"identity,omitempty"`
	NewWaID  string `json:"new_wa_id,omitempty"`
	WaID     string `json:"wa_id,omitempty"`
}

// WebhookIdentity represents identity information
type WebhookIdentity struct {
	Acknowledged     bool   `json:"acknowledged"`
	CreatedTimestamp string `json:"created_timestamp"`
	Hash             string `json:"hash"`
}

// WebhookReferral represents referral information
type WebhookReferral struct {
	SourceURL    string `json:"source_url"`
	SourceID     string `json:"source_id,omitempty"`
	SourceType   string `json:"source_type"`
	Headline     string `json:"headline,omitempty"`
	Body         string `json:"body,omitempty"`
	MediaType    string `json:"media_type,omitempty"`
	ImageURL     string `json:"image_url,omitempty"`
	VideoURL     string `json:"video_url,omitempty"`
	ThumbnailURL string `json:"thumbnail_url,omitempty"`
}

// WebhookStatus represents a message status update
type WebhookStatus struct {
	ID           string               `json:"id"`        // Message ID
	Status       string               `json:"status"`    // "sent", "delivered", "read", "failed"
	Timestamp    string               `json:"timestamp"` // Unix timestamp as string
	RecipientID  string               `json:"recipient_id"`
	Conversation *WebhookConversation `json:"conversation,omitempty"`
	Pricing      *WebhookPricing      `json:"pricing,omitempty"`
	Errors       []WebhookError       `json:"errors,omitempty"`
}

// WebhookConversation contains conversation details
type WebhookConversation struct {
	ID                  string        `json:"id"`
	ExpirationTimestamp string        `json:"expiration_timestamp,omitempty"`
	Origin              WebhookOrigin `json:"origin"`
}

// WebhookOrigin contains conversation origin
type WebhookOrigin struct {
	Type string `json:"type"`
}

// WebhookPricing contains pricing information
type WebhookPricing struct {
	Billable     bool   `json:"billable"`
	PricingModel string `json:"pricing_model"`
	Category     string `json:"category"`
}

// WebhookError represents an error in status update
type WebhookError struct {
	Code  int    `json:"code"`
	Title string `json:"title"`
}

// TokenDebugResponse represents the response from debug_token endpoint
type TokenDebugResponse struct {
	Data TokenDebugData `json:"data"`
}

// TokenDebugData contains token validation information
type TokenDebugData struct {
	AppID               string   `json:"app_id"`
	Type                string   `json:"type"`
	Application         string   `json:"application"`
	DataAccessExpiresAt int64    `json:"data_access_expires_at"`
	ExpiresAt           int64    `json:"expires_at"`
	IsValid             bool     `json:"is_valid"`
	IssuedAt            int64    `json:"issued_at,omitempty"`
	Scopes              []string `json:"scopes"`
	UserID              string   `json:"user_id"`
}

// PhoneNumberDetails represents phone number information from the API
type PhoneNumberDetails struct {
	ID                     string         `json:"id"`
	VerifiedName           string         `json:"verified_name"`
	CodeVerificationStatus string         `json:"code_verification_status"`
	DisplayPhoneNumber     string         `json:"display_phone_number"`
	QualityRating          string         `json:"quality_rating"`
	PlatformType           string         `json:"platform_type"`
	Throughput             ThroughputInfo `json:"throughput"`
}

// ThroughputInfo contains throughput information
type ThroughputInfo struct {
	Level string `json:"level"`
}

// BusinessAccountDetails represents business account information
type BusinessAccountDetails struct {
	ID                       string `json:"id"`
	Name                     string `json:"name"`
	TimezoneID               string `json:"timezone_id"`
	MessageTemplateNamespace string `json:"message_template_namespace,omitempty"`
}

// TemplateStatusValue represents the value payload in a message_template_status_update webhook.
// This is a distinct shape from WebhookValue — Meta does not include messaging_product or
// metadata in these notifications.
type TemplateStatusValue struct {
	Event            string   `json:"event"`             // e.g. "TEMPLATE_APPROVED", "TEMPLATE_REJECTED"
	TemplateName     string   `json:"template_name"`     // name used during upload
	TemplateID       string   `json:"template_id"`       // Meta-assigned template ID
	Language         string   `json:"language"`          // e.g. "en_US"
	Status           string   `json:"status"`            // "APPROVED", "REJECTED", "PENDING"
	RejectionReasons []string `json:"rejection_reasons"` // non-empty only when Status == "REJECTED"
}

// ---------------------------------------------------------------------------
// Outgoing message types (sending)
// ---------------------------------------------------------------------------

// LocationObject is used when sending a location message
type LocationObject struct {
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
	Name      string  `json:"name,omitempty"`
	Address   string  `json:"address,omitempty"`
}

// SendContactObject is a contact card in an outgoing contacts message
type SendContactObject struct {
	Name      ContactNameObj      `json:"name"`
	Addresses []ContactAddressObj `json:"addresses,omitempty"`
	Emails    []ContactEmailObj   `json:"emails,omitempty"`
	Phones    []ContactPhoneObj   `json:"phones,omitempty"`
	Org       *ContactOrgObj      `json:"org,omitempty"`
	URLs      []ContactURLObj     `json:"urls,omitempty"`
}

type ContactNameObj struct {
	FormattedName string `json:"formatted_name"`
	FirstName     string `json:"first_name,omitempty"`
	LastName      string `json:"last_name,omitempty"`
	MiddleName    string `json:"middle_name,omitempty"`
	Suffix        string `json:"suffix,omitempty"`
	Prefix        string `json:"prefix,omitempty"`
}

type ContactAddressObj struct {
	City        string `json:"city,omitempty"`
	Country     string `json:"country,omitempty"`
	CountryCode string `json:"country_code,omitempty"`
	State       string `json:"state,omitempty"`
	Street      string `json:"street,omitempty"`
	Type        string `json:"type,omitempty"`
	Zip         string `json:"zip,omitempty"`
}

type ContactEmailObj struct {
	Email string `json:"email,omitempty"`
	Type  string `json:"type,omitempty"`
}

type ContactPhoneObj struct {
	Phone string `json:"phone,omitempty"`
	Type  string `json:"type,omitempty"`
}

type ContactOrgObj struct {
	Company    string `json:"company,omitempty"`
	Department string `json:"department,omitempty"`
	Title      string `json:"title,omitempty"`
}

type ContactURLObj struct {
	URL  string `json:"url,omitempty"`
	Type string `json:"type,omitempty"`
}

// InteractiveObject is the payload for interactive messages (buttons, list, flow)
type InteractiveObject struct {
	Type    string              `json:"type"` // "button", "list", "flow"
	Header  *InteractiveHeader  `json:"header,omitempty"`
	Body    *InteractiveBody    `json:"body"`
	Footer  *InteractiveFooter  `json:"footer,omitempty"`
	Buttons []InteractiveButton `json:"buttons,omitempty"` // type "button": 1-3 reply buttons
	Action  *InteractiveAction  `json:"action,omitempty"`  // type "list" or "flow"
}

type InteractiveHeader struct {
	Type     string       `json:"type"` // "text", "image", "video", "document"
	Text     string       `json:"text,omitempty"`
	Image    *MediaObject `json:"image,omitempty"`
	Video    *MediaObject `json:"video,omitempty"`
	Document *MediaObject `json:"document,omitempty"`
}

type InteractiveBody struct {
	Text string `json:"text"`
}

type InteractiveFooter struct {
	Text string `json:"text"`
}

type InteractiveButton struct {
	Type  string                 `json:"type"` // "reply"
	Reply InteractiveButtonReply `json:"reply"`
}

type InteractiveButtonReply struct {
	ID    string `json:"id"`    // up to 20 chars; returned in webhook reply
	Title string `json:"title"` // up to 20 chars; displayed on button
}

// InteractiveAction is shared by list and flow interactive messages
type InteractiveAction struct {
	// list fields
	Button   string               `json:"button,omitempty"`   // label on the list button
	Sections []InteractiveSection `json:"sections,omitempty"` // 1-10 sections
	// flow fields
	Name       string            `json:"name,omitempty"` // "flow"
	Parameters *FlowActionParams `json:"parameters,omitempty"`
}

type InteractiveSection struct {
	Title string                  `json:"title,omitempty"`
	Rows  []InteractiveSectionRow `json:"rows"` // 1-10 rows
}

type InteractiveSectionRow struct {
	ID          string `json:"id"`                    // up to 20 chars
	Title       string `json:"title"`                 // up to 60 chars
	Description string `json:"description,omitempty"` // up to 72 chars
}

// FlowActionParams defines parameters when sending an interactive flow message
type FlowActionParams struct {
	Type      string         `json:"type"` // "payload" or "unpublished"
	FlowToken string         `json:"flow_token"`
	Name      string         `json:"name"` // initial screen name
	Data      map[string]any `json:"data"` // dynamic key/value pairs for the screen
}

// TemplateMessageObject defines a template message for sending
type TemplateMessageObject struct {
	Name       string                  `json:"name"`
	Language   TemplateLanguage        `json:"language"`
	Components []TemplateSendComponent `json:"components,omitempty"`
}

type TemplateLanguage struct {
	Code   string `json:"code"`             // e.g. "en_US", "en"
	Policy string `json:"policy,omitempty"` // "deterministic"
}

type TemplateSendComponent struct {
	Type       string              `json:"type"`               // "header", "body", "buttons"
	SubType    string              `json:"sub_type,omitempty"` // "quick_reply" or "url" (buttons only)
	Index      string              `json:"index,omitempty"`    // "0","1","2" (buttons only)
	Parameters []TemplateParameter `json:"parameters"`
}

type TemplateParameter struct {
	Type     string          `json:"type"` // "text","currency","date_time","image","video","document","location","payload"
	Text     string          `json:"text,omitempty"`
	Currency *CurrencyObject `json:"currency,omitempty"`
	DateTime *DateTimeObject `json:"date_time,omitempty"`
	Image    *MediaObject    `json:"image,omitempty"`
	Video    *MediaObject    `json:"video,omitempty"`
	Document *MediaObject    `json:"document,omitempty"`
	Location *LocationObject `json:"location,omitempty"`
	Payload  string          `json:"payload,omitempty"` // quick_reply button payload
}

type CurrencyObject struct {
	Currency string `json:"currency"` // ISO 4217
	Amount   string `json:"amount"`
}

type DateTimeObject struct {
	Raw string `json:"raw"` // RFC 3339 datetime string
}

// ReactionMessage is the body sent to react to an existing message.
// Uses "message_type" (not "type") at the top level — distinct from SendMessageRequest.
type ReactionMessage struct {
	MessagingProduct string         `json:"messaging_product"` // "whatsapp"
	MessageType      string         `json:"message_type"`      // "reaction"
	Reaction         ReactionObject `json:"reaction"`
}

type ReactionObject struct {
	MessageID string `json:"message_id"`
	Emoji     string `json:"emoji"`
}

// ReadReceiptMessage marks a received message as read
type ReadReceiptMessage struct {
	MessagingProduct string `json:"messaging_product"` // "whatsapp"
	Status           string `json:"status"`            // "read"
	MessageID        string `json:"message_id"`
}

// ---------------------------------------------------------------------------
// Template management (CRUD)
// ---------------------------------------------------------------------------

type TemplateListResponse struct {
	Data   []TemplateInfo `json:"data"`
	Paging *PagingInfo    `json:"paging,omitempty"`
}

type TemplateInfo struct {
	ID               string                 `json:"id"`
	Name             string                 `json:"name"`
	Status           string                 `json:"status"` // APPROVED, PENDING, REJECTED
	Language         string                 `json:"language"`
	Category         string                 `json:"category"` // MARKETING, UTILITY, AUTHENTICATION
	CreatedAt        string                 `json:"created_at"`
	Components       []TemplateComponentDef `json:"components"`
	RejectionReasons []string               `json:"rejection_reasons,omitempty"`
	QualityScore     any                    `json:"quality_score,omitempty"`
}

type TemplateComponentDef struct {
	Type    string                    `json:"type"`             // HEADER, BODY, FOOTER, BUTTONS
	Format  string                    `json:"format,omitempty"` // TEXT, IMAGE, VIDEO, DOCUMENT, LOCATION
	Text    string                    `json:"text,omitempty"`
	Buttons []TemplateButtonDef       `json:"buttons,omitempty"`
	Example *TemplateComponentExample `json:"example,omitempty"`
}

type TemplateButtonDef struct {
	Type        string `json:"type"` // PHONE_NUMBER, URL, QUICK_REPLY, COPY_CODE
	Text        string `json:"text"`
	URL         string `json:"url,omitempty"`
	PhoneNumber string `json:"phone_number,omitempty"`
	Dynamic     bool   `json:"dynamic,omitempty"`
}

type TemplateComponentExample struct {
	HeaderHandle []string   `json:"header_handle,omitempty"`
	BodyExample  [][]string `json:"body_example,omitempty"`
}

type TemplateUploadRequest struct {
	Name                string                    `json:"name"`
	Language            string                    `json:"language"`
	Category            string                    `json:"category"` // MARKETING, UTILITY, AUTHENTICATION
	Components          []TemplateUploadComponent `json:"components"`
	AllowCategoryChange bool                      `json:"allow_category_change,omitempty"`
}

type TemplateUploadComponent struct {
	Type    string                 `json:"type"`             // HEADER, BODY, FOOTER, BUTTONS
	Format  string                 `json:"format,omitempty"` // TEXT, IMAGE, VIDEO, DOCUMENT, LOCATION (HEADER only)
	Text    string                 `json:"text,omitempty"`
	Buttons []TemplateUploadButton `json:"buttons,omitempty"`
	Example *TemplateUploadExample `json:"example,omitempty"`
}

type TemplateUploadButton struct {
	Type        string   `json:"type"` // PHONE_NUMBER, URL, QUICK_REPLY, COPY_CODE
	Text        string   `json:"text"`
	URL         string   `json:"url,omitempty"`
	PhoneNumber string   `json:"phone_number,omitempty"`
	Example     []string `json:"example,omitempty"` // example values for dynamic parts
}

type TemplateUploadExample struct {
	HeaderHandle []string   `json:"header_handle,omitempty"`
	BodyExample  [][]string `json:"body_example,omitempty"`
}

type TemplateUploadResponse struct {
	Data TemplateUploadData `json:"data"`
}

type TemplateUploadData struct {
	ID     string `json:"id"`
	Status string `json:"status"`
}

// ---------------------------------------------------------------------------
// Flow management (CRUD)
// ---------------------------------------------------------------------------

type FlowListResponse struct {
	Data   []FlowInfo  `json:"data"`
	Paging *PagingInfo `json:"paging,omitempty"`
}

type FlowInfo struct {
	ID               string   `json:"id"`
	Name             string   `json:"name"`
	Status           string   `json:"status"` // DRAFT, PUBLISHED, DEPRECATED, BLOCKED, ERROR
	Categories       []string `json:"categories"`
	CreatedAt        string   `json:"created_at"`
	UpdatedAt        string   `json:"updated_at"`
	EndpointURL      string   `json:"endpoint_url,omitempty"`
	PreviewURL       string   `json:"preview_url,omitempty"`
	SignedPreviewURL string   `json:"signed_preview_url,omitempty"`
	SignedFlowURL    string   `json:"signed_flow_url,omitempty"`
}

type FlowCreateRequest struct {
	Name        string   `json:"name"`
	Categories  []string `json:"categories"` // e.g. ["SIGN_IN"]
	EndpointURL string   `json:"endpoint_url,omitempty"`
	CloneFlowID string   `json:"clone_flow_id,omitempty"`
}

type FlowCreateResponse struct {
	Data FlowCreateData `json:"data"`
}

type FlowCreateData struct {
	ID     string `json:"id"`
	Status string `json:"status"`
}

type FlowActionResponse struct {
	Data FlowActionData `json:"data"`
}

type FlowActionData struct {
	Success bool   `json:"success"`
	Status  string `json:"status,omitempty"`
}

// ---------------------------------------------------------------------------
// Phone number management
// ---------------------------------------------------------------------------

type PhoneNumberListResponse struct {
	Data   []PhoneNumberListItem `json:"data"`
	Paging *PagingInfo           `json:"paging,omitempty"`
}

type PhoneNumberListItem struct {
	ID                     string         `json:"id"`
	DisplayPhoneNumber     string         `json:"display_phone_number"`
	PhoneNumber            string         `json:"phone_number"`
	VerifiedName           string         `json:"verified_name"`
	CodeVerificationStatus string         `json:"code_verification_status"`
	QualityRating          string         `json:"quality_rating"`
	Throughput             ThroughputInfo `json:"throughput"`
}

type RequestCodeRequest struct {
	CertificateData string `json:"certificate_data,omitempty"`
}

type RequestCodeResponse struct {
	Data RequestCodeData `json:"data"`
}

type RequestCodeData struct {
	MessageStatus string `json:"message_status"` // "CODE_SENT"
}

type VerifyCodeRequest struct {
	Code string `json:"code"`
}

type VerifyCodeResponse struct {
	Data VerifyCodeData `json:"data"`
}

type VerifyCodeData struct {
	MessageStatus string `json:"message_status"` // "CODE_VERIFIED"
}

type RegisterPhoneNumberRequest struct {
	MessagingProduct string `json:"messaging_product"` // always "whatsapp"
	Pin              string `json:"pin"`               // 6-digit two-step verification PIN
}

type RegisterPhoneNumberResponse struct {
	Success bool `json:"success"`
}

// ---------------------------------------------------------------------------
// Business profile
// ---------------------------------------------------------------------------

// BusinessProfile represents a WhatsApp Business profile returned by the API.
type BusinessProfile struct {
	About         string   `json:"about,omitempty"`
	Address       string   `json:"address,omitempty"`
	Description   string   `json:"description,omitempty"`
	Email         string   `json:"email,omitempty"`
	Websites      []string `json:"websites,omitempty"`
	Vertical      string   `json:"vertical,omitempty"`
	ProfilePicURL string   `json:"profile_picture_url,omitempty"`
}

// BusinessProfileUpdate is the payload sent to update business profile fields.
// Only populated fields are sent; omit a field to leave it unchanged.
type BusinessProfileUpdate struct {
	MessagingProduct string   `json:"messaging_product"` // always "whatsapp"
	About            string   `json:"about,omitempty"`
	Address          string   `json:"address,omitempty"`
	Description      string   `json:"description,omitempty"`
	Email            string   `json:"email,omitempty"`
	Websites         []string `json:"websites,omitempty"`
	Vertical         string   `json:"vertical,omitempty"`
}

// ---------------------------------------------------------------------------
// Catalog / commerce
// ---------------------------------------------------------------------------

// CatalogListResponse is the response from listing catalogs on a WABA.
type CatalogListResponse struct {
	Data   []CatalogInfo `json:"data"`
	Paging *PagingInfo   `json:"paging,omitempty"`
}

// CatalogInfo represents a single product catalog.
type CatalogInfo struct {
	ID           string `json:"id"`
	Name         string `json:"name"`
	ProductCount int    `json:"product_count,omitempty"`
}

// ProductListResponse is the response from listing products in a catalog.
type ProductListResponse struct {
	Data   []ProductInfo `json:"data"`
	Paging *PagingInfo   `json:"paging,omitempty"`
}

// ProductInfo represents a product in a catalog.
type ProductInfo struct {
	ProductRetailerID string  `json:"product_retailer_id"`
	Name              string  `json:"name,omitempty"`
	Description       string  `json:"description,omitempty"`
	ImageURL          string  `json:"image_url,omitempty"`
	BasePrice         float64 `json:"base_price,omitempty"`
	Currency          string  `json:"currency,omitempty"`
	Availability      string  `json:"availability,omitempty"`
	Category          string  `json:"category,omitempty"`
}

// ProductItem is a product reference used inside a product-list message section.
type ProductItem struct {
	ProductRetailerID string `json:"product_retailer_id"`
}

// ProductListSection is one section in a product-list interactive message.
type ProductListSection struct {
	Title        string        `json:"title"`
	ProductItems []ProductItem `json:"product_items"`
}

// ---------------------------------------------------------------------------
// Shared / pagination
// ---------------------------------------------------------------------------

type PagingInfo struct {
	Cursors PagingCursors `json:"cursors"`
	Next    string        `json:"next,omitempty"`
}

type PagingCursors struct {
	Before string `json:"before"`
	After  string `json:"after"`
}
