package businessapi

import (
	"context"
	"net/url"
)

// ListFlows returns all flows for the business account.
func (c *Client) ListFlows(ctx context.Context) (*FlowListResponse, error) {
	wabaID, err := c.resolveWABAID(ctx)
	if err != nil {
		return nil, err
	}

	params := url.Values{
		"fields": {"id,name,status,categories,created_at,updated_at,endpoint_url,preview_url,signed_preview_url,signed_flow_url"},
	}

	var resp FlowListResponse
	if err := c.graphAPIGet(ctx, wabaID+"/flows", params, &resp); err != nil {
		return nil, err
	}
	return &resp, nil
}

// CreateFlow creates a new flow and returns its ID.
func (c *Client) CreateFlow(ctx context.Context, flow FlowCreateRequest) (*FlowCreateResponse, error) {
	wabaID, err := c.resolveWABAID(ctx)
	if err != nil {
		return nil, err
	}

	var resp FlowCreateResponse
	if err := c.graphAPIPost(ctx, wabaID+"/flows", flow, &resp); err != nil {
		return nil, err
	}
	return &resp, nil
}

// GetFlow returns details for a single flow.
func (c *Client) GetFlow(ctx context.Context, flowID string) (*FlowInfo, error) {
	params := url.Values{
		"fields": {"id,name,status,categories,created_at,updated_at,endpoint_url,preview_url,signed_preview_url,signed_flow_url"},
	}

	var resp FlowInfo
	if err := c.graphAPIGet(ctx, flowID, params, &resp); err != nil {
		return nil, err
	}
	return &resp, nil
}

// UpdateFlowAssets uploads a screens JSON definition to an existing flow (must be in DRAFT).
func (c *Client) UpdateFlowAssets(ctx context.Context, flowID string, screensJSON string) error {
	fields := map[string]string{
		"asset_type": "SCREENS_JSON",
		"asset_data": screensJSON,
	}

	var resp FlowActionResponse
	return c.graphAPIPostForm(ctx, flowID+"/assets", fields, &resp)
}

// PublishFlow transitions a DRAFT flow to PUBLISHED.
func (c *Client) PublishFlow(ctx context.Context, flowID string) error {
	var resp FlowActionResponse
	return c.graphAPIPost(ctx, flowID+"?action=PUBLISH", nil, &resp)
}

// DeprecateFlow transitions a PUBLISHED flow to DEPRECATED.
// Deprecated flows block new sessions but remain usable by sessions already in progress.
func (c *Client) DeprecateFlow(ctx context.Context, flowID string) error {
	var resp FlowActionResponse
	return c.graphAPIPost(ctx, flowID+"?action=DEPRECATE", nil, &resp)
}

// DeleteFlow permanently removes a flow.
func (c *Client) DeleteFlow(ctx context.Context, flowID string) error {
	return c.graphAPIDelete(ctx, flowID, nil)
}
