package businessapi

import (
	"context"
	"fmt"
	"net/url"
)

func (c *Client) resolveWABAID(ctx context.Context) (string, error) {
	if c.wabaID != "" {
		return c.wabaID, nil
	}

	if c.config.WABAId != "" {
		c.wabaID = c.config.WABAId
		return c.wabaID, nil
	}

	id, err := c.fetchWABAID(ctx)
	if err != nil {
		return "", fmt.Errorf("could not resolve WABA ID: %w", err)
	}

	c.wabaID = id
	return c.wabaID, nil
}

// ListTemplates returns all message templates for the business account.
// Uses the WhatsApp Business Account (WABA) ID.
func (c *Client) ListTemplates(ctx context.Context) (*TemplateListResponse, error) {
	wabaID, err := c.resolveWABAID(ctx)
	if err != nil {
		return nil, err
	}

	params := url.Values{
		"fields": {"id,name,status,language,category,created_at,components,quality_score"},
	}

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

// UploadTemplate creates a new message template.
func (c *Client) UploadTemplate(ctx context.Context, tmpl TemplateUploadRequest) (*TemplateUploadResponse, error) {
	wabaID, err := c.resolveWABAID(ctx)
	if err != nil {
		return nil, err
	}

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

// DeleteTemplate deletes a template by name and language.
func (c *Client) DeleteTemplate(ctx context.Context, name, language string) error {
	wabaID, err := c.resolveWABAID(ctx)
	if err != nil {
		return err
	}

	params := url.Values{
		"name":     {name},
		"language": {language},
	}
	return c.graphAPIDelete(ctx, wabaID+"/message_templates", params)
}
