package route53

import (
	"log/slog"
	"os"
	"strconv"
	"time"

	"github.com/libdns/route53"
	"go.uber.org/zap/exp/zapslog"

	"github.com/caddyserver/caddy/v2"
	"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
)

// Provider wraps the provider implementation as a Caddy module.
type Provider struct {
	*route53.Provider

	// DebugLogging forwards structured events from libdns/route53 (zone
	// resolution, change submission, sync waits) to Caddy's logger. The
	// underlying library emits at Debug level except for ambiguous-zone
	// warnings, so set Caddy's log level to debug to actually see them.
	DebugLogging bool `json:"debug_logging,omitempty"`
}

func init() {
	caddy.RegisterModule(Provider{})
}

// CaddyModule returns the Caddy module information.
func (Provider) CaddyModule() caddy.ModuleInfo {
	return caddy.ModuleInfo{
		ID: "dns.providers.route53",
		New: func() caddy.Module {
			return &Provider{Provider: new(route53.Provider)}
		},
	}
}

// Provision implements the Provisioner interface to initialize the AWS Client.
func (p *Provider) Provision(ctx caddy.Context) error {
	repl := caddy.NewReplacer()
	p.Profile = repl.ReplaceAll(p.Profile, "")
	p.AccessKeyId = repl.ReplaceAll(p.AccessKeyId, "")
	p.SecretAccessKey = repl.ReplaceAll(p.SecretAccessKey, "")
	p.SessionToken = repl.ReplaceAll(p.SessionToken, "")
	p.Region = repl.ReplaceAll(p.Region, "")
	if p.DebugLogging {
		p.Provider.Logger = slog.New(zapslog.NewHandler(
			ctx.Logger().Core(),
			zapslog.WithName(string(p.CaddyModule().ID)),
		))
	}
	return nil
}

// UnmarshalCaddyfile sets up the DNS provider from Caddyfile tokens. Syntax:
//
//	route53 {
//		region <string>
//		profile <string>
//		access_key_id <string>
//		secret_access_key <string>
//		session_token <string>
//		max_retries <int>
//		route53_max_wait <duration>
//		wait_for_route53_sync <bool>
//		skip_route53_sync_on_delete <bool>
//		hosted_zone_id <string>
//		debug_logging <bool>
//	}
func (p *Provider) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
	for d.Next() {
		if d.NextArg() {
			return d.ArgErr()
		}
		p.Provider.Region = os.Getenv("AWS_REGION")
		if p.Provider.Region == "" {
			p.Provider.Region = "us-east-1"
		}
		p.Provider.WaitForRoute53Sync = false
		p.Provider.SkipRoute53SyncOnDelete = true
		for nesting := d.Nesting(); d.NextBlock(nesting); {
			switch d.Val() {
			case "wait_for_route53_sync", "wait_for_propagation": // backward compat
				if d.NextArg() {
					if wait, err := strconv.ParseBool(d.Val()); err == nil {
						p.Provider.WaitForRoute53Sync = wait
					}
				}
				if d.NextArg() {
					return d.ArgErr()
				}
			case "skip_route53_sync_on_delete":
				if d.NextArg() {
					if skip, err := strconv.ParseBool(d.Val()); err == nil {
						p.Provider.SkipRoute53SyncOnDelete = skip
					}
				}
				if d.NextArg() {
					return d.ArgErr()
				}
			case "route53_max_wait", "max_wait_dur": // backward compat
				if d.NextArg() {
					if dur, err := time.ParseDuration(d.Val()); err == nil {
						p.Provider.Route53MaxWait = dur
					} else if durInt, intErr := strconv.ParseInt(d.Val(), 10, 64); intErr == nil {
						// backward compat: treat plain integers as seconds
						p.Provider.Route53MaxWait = time.Duration(durInt * int64(time.Second))
					}
				}
				if d.NextArg() {
					return d.ArgErr()
				}
			case "max_retries":
				if d.NextArg() {
					p.Provider.MaxRetries, _ = strconv.Atoi(d.Val())
				}
				if d.NextArg() {
					return d.ArgErr()
				}
			case "profile", "aws_profile":
				if d.NextArg() {
					p.Provider.Profile = d.Val()
				}
				if d.NextArg() {
					return d.ArgErr()
				}
			case "access_key_id":
				if d.NextArg() {
					p.Provider.AccessKeyId = d.Val()
				}
				if d.NextArg() {
					return d.ArgErr()
				}
			case "secret_access_key":
				if d.NextArg() {
					p.Provider.SecretAccessKey = d.Val()
				}
				if d.NextArg() {
					return d.ArgErr()
				}
			case "session_token", "token":
				if d.NextArg() {
					p.Provider.SessionToken = d.Val()
				}
				if d.NextArg() {
					return d.ArgErr()
				}
			case "region":
				if d.NextArg() {
					p.Provider.Region = d.Val()
				}
				if d.NextArg() {
					return d.ArgErr()
				}
			case "hosted_zone_id":
				if d.NextArg() {
					p.Provider.HostedZoneID = d.Val()
				}
				if d.NextArg() {
					return d.ArgErr()
				}
			case "debug_logging":
				if d.NextArg() {
					if v, err := strconv.ParseBool(d.Val()); err == nil {
						p.DebugLogging = v
					}
				}
				if d.NextArg() {
					return d.ArgErr()
				}
			default:
				return d.Errf("unrecognized subdirective '%s'", d.Val())
			}
		}
	}

	return nil
}

// Interface guards.
var (
	_ caddyfile.Unmarshaler = (*Provider)(nil)
	_ caddy.Provisioner     = (*Provider)(nil)
)
