/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 */
package filecli

import (
	"net/url"
	"path"
	"strconv"
	"strings"
)

const (
	PathTypeIdentic = "identic"
	PathTypePrefix  = "prefix"
	PathTypeRegexp  = "regexp"
)

type Referer struct {
	urlobj     *url.URL
	user, pass string
	resource   string
	values     url.Values
}

func ParsePath(rawpath string) (*Referer, error) {
	ref := &Referer{
		values: url.Values{},
	}
	if !strings.Contains(rawpath, "://") {
		rawpath = "https://" + rawpath
	}
	urlobj, err := url.Parse(rawpath)
	if err != nil {
		return ref, err
	}
	if urlobj.User != nil {
		ref.user = urlobj.User.Username()
		ref.pass, _ = urlobj.User.Password()
		urlobj.User = nil
	}
	ref.resource = path.Join("/", urlobj.Path)
	urlobj.Path = "/"
	ref.urlobj = urlobj
	ref.values = urlobj.Query()
	return ref, err
}

func (ref *Referer) Raw() string {
	res := path.Join(ref.urlobj.Host, ref.resource)
	query := ref.values.Encode()
	if query != "" {
		return res + "?" + query
	}
	return res
}

func (ref *Referer) SetResource(resource string) {
	ref.resource = path.Join("/", resource)
}

func (ref *Referer) JoinResource(resource string) {
	ref.resource = path.Join("/", ref.resource, resource)
}

func (ref *Referer) PathType(typ string) {
	ref.values.Set("pathType", typ)
}

func (ref *Referer) DryRun(yesno bool) {
	ref.values.Set("dryRun", strconv.FormatBool(yesno))
}

func (ref *Referer) FileEP() string {
	curl := ref.urlobj.JoinPath("/v3/api/file/", ref.resource)
	return curl.String()
}

func (ref *Referer) FilesEP() string {
	curl := ref.urlobj.JoinPath("/v3/api/files/", ref.resource)
	return curl.String()
}

func (ref *Referer) CollectionEP() string {
	curl := ref.urlobj.JoinPath("/v3/api/collection/", ref.resource)
	return curl.String()
}

func (ref *Referer) CollectionsEP() string {
	curl := ref.urlobj.JoinPath("/v3/api/collections/", ref.resource)
	return curl.String()
}

func (ref *Referer) CheckEP() string {
	curl := ref.urlobj.JoinPath("/v3/api/checker/", ref.resource)
	return curl.String()
}

func (ref *Referer) Userinfo() (string, string) {
	return ref.user, ref.pass
}

func (ref *Referer) SetUserinfo(user, pass string) {
	if user != "" && pass != "" {
		ref.user, ref.pass = user, pass
	}
}
