package connector

import (
	"encoding/json"
	"errors"
	"htwkalender/ical/model"
	"log/slog"
)

func GetFeedByToken(host string, token string) (model.FeedRecord, error) {
	var feed model.FeedRecord

	// /api/collections/feeds/records/{id}

	response, err := RequestApi(host, "/api/collections/feeds/records/"+token)
	if err != nil {
		slog.Error("Failed to get feed record", "error", err)
		return model.FeedRecord{}, err
	}

	// parse the response body json to FeedRecord struct
	feed, err = parseResponse(response.Body())
	if err != nil {
		slog.Error("Failed to read response body", "error", err)
		return model.FeedRecord{}, err
	}

	return feed, nil

}

func parseResponse(response []byte) (model.FeedRecord, error) {
	var feedRecord model.FeedRecord

	err := json.Unmarshal(response, &feedRecord)
	if err != nil {
		return model.FeedRecord{}, err
	}

	return feedRecord, nil
}

func DeleteFeedRecord(app model.AppType, token string) error {
	err := DeleteRequestApi(app.DataManagerURL, "/api/feed?token="+token)
	if err != nil {
		return err
	}

	return nil
}

func GetModuleWithEvents(app model.AppType, module model.FeedModule) (model.Module, error) {
	var modules model.Module

	response, err := RequestApi(app.DataManagerURL, "/api/module?uuid="+module.UUID)
	if err != nil {
		return model.Module{}, err
	}

	// parse the response body json to Events struct
	modules, err = parseModuleResponse(response.Body())
	if err != nil {
		slog.Error("Failed to read response body", "error", err)
		return model.Module{}, err
	}

	return modules, nil
}

func parseModuleResponse(body []byte) (model.Module, error) {
	var module model.Module

	err := json.Unmarshal(body, &module)
	if err != nil {
		return model.Module{}, err
	}

	return module, nil
}

func SaveFeedRecord(app model.AppType, modules []model.FeedCollection) (string, error) {
	var token string

	response, err := PostRequestApi(app.DataManagerURL, "/api/feed", modules)
	if err != nil {
		return "", err
	}

	if response.StatusCode() != 200 {
		return "", errors.New("failed to save feed")
	}

	// parse the response body json to string
	err = json.Unmarshal(response.Body(), &token)
	if err != nil {
		return "", err
	}

	return token, nil
}
