package v1alpha1

import (
	"context"

	"git.kocoder.xyz/kocoder/portforwarder/api/types/v1alpha1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"
)

type IngressrouteInterface interface {
	List(ctx context.Context, opts metav1.ListOptions) (*v1alpha1.IngressRouteList, error)
	Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1alpha1.IngressRoute, error)
	Create(ctx context.Context, ir *v1alpha1.IngressRoute) (*v1alpha1.IngressRoute, error)
	Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)
	Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error
}

type ingressrouteClient struct {
	restClient rest.Interface
	ns         string
	rn         string
}

func (c ingressrouteClient) List(ctx context.Context, opts metav1.ListOptions) (*v1alpha1.IngressRouteList, error) {
	result := v1alpha1.IngressRouteList{}
	err := c.restClient.Get().Namespace(c.ns).Resource(c.rn).VersionedParams(&opts, scheme.ParameterCodec).Do(ctx).Into(&result)
	return &result, err
}

func (c ingressrouteClient) Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1alpha1.IngressRoute, error) {
	result := v1alpha1.IngressRoute{}
	err := c.restClient.Get().Namespace(c.ns).Resource(c.rn).Name(name).VersionedParams(&opts, scheme.ParameterCodec).Do(ctx).Into(&result)
	return &result, err
}

func (c ingressrouteClient) Create(ctx context.Context, ir *v1alpha1.IngressRoute) (*v1alpha1.IngressRoute, error) {
	result := v1alpha1.IngressRoute{}
	err := c.restClient.Post().Namespace(c.ns).Resource(c.rn).Body(ir).Do(ctx).Into(&result)
	return &result, err
}

func (c ingressrouteClient) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {
	opts.Watch = true
	return c.restClient.Get().Namespace(c.ns).Resource(c.rn).VersionedParams(&opts, scheme.ParameterCodec).Watch(ctx)
}

func (c ingressrouteClient) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {
	return c.restClient.Delete().Namespace(c.ns).Resource(c.rn).Name(name).Body(&opts).Do(ctx).Error()
}
