package controller

import (
	"context"
	"errors"

	"git.schreifuchs.ch/schreifuchs/warehouse/api"
	"git.schreifuchs.ch/schreifuchs/warehouse/model"
	"gorm.io/gorm"
)

func (c *Controller) GetBuckets(ctx context.Context, request api.GetBucketsRequestObject) (api.GetBucketsResponseObject, error) {

	buckets, err := c.db.FindApiBuckets(*request.Params.Limit, *request.Params.Offset)
	if err != nil {
		return api.GetBuckets500Response{}, nil
	}

	t := len(buckets)

	return api.GetBuckets200JSONResponse{
		Items: &buckets,
		Total: &t,
	}, nil
}

func (c *Controller) PostBuckets(ctx context.Context, request api.PostBucketsRequestObject) (api.PostBucketsResponseObject, error) {

	b := &model.Bucket{}
	b.Name = *request.Body.Name

	c.db.InsertBucket(b)

	return api.PostBuckets409Response{}, nil
}

func (c *Controller) DeleteBucketsBucketName(ctx context.Context, request api.DeleteBucketsBucketNameRequestObject) (api.DeleteBucketsBucketNameResponseObject, error) {
	if err := c.db.DeleteBucketByName(request.BucketName); errors.Is(err, gorm.ErrRecordNotFound) {
		return api.DeleteBucketsBucketName404Response{}, nil
	} else if err != nil {
		return api.DeleteBucketsBucketName500Response{}, err
	}
	return api.DeleteBucketsBucketName204Response{}, nil
}

func (c *Controller) GetBucketsBucketNameObjects(ctx context.Context, request api.GetBucketsBucketNameObjectsRequestObject) (api.GetBucketsBucketNameObjectsResponseObject, error) {
	return api.GetBucketsBucketNameObjects404Response{}, nil
}

func (c *Controller) DeleteBucketsBucketNameObjectsObjectKey(ctx context.Context, request api.DeleteBucketsBucketNameObjectsObjectKeyRequestObject) (api.DeleteBucketsBucketNameObjectsObjectKeyResponseObject, error) {
	return api.DeleteBucketsBucketNameObjectsObjectKey500Response{}, nil
}

func (c *Controller) GetBucketsBucketNameObjectsObjectKey(ctx context.Context, request api.GetBucketsBucketNameObjectsObjectKeyRequestObject) (api.GetBucketsBucketNameObjectsObjectKeyResponseObject, error) {
	return api.GetBucketsBucketNameObjectsObjectKey404Response{}, nil
}

func (c *Controller) PutBucketsBucketNameObjectsObjectKey(ctx context.Context, request api.PutBucketsBucketNameObjectsObjectKeyRequestObject) (api.PutBucketsBucketNameObjectsObjectKeyResponseObject, error) {
	return api.PutBucketsBucketNameObjectsObjectKey500Response{}, nil
}
