package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"code.gitea.io/sdk/gitea"
)

type VersionInfo struct {
	Version string `json:"version"`
}

func main() {
	client, err := createGiteaClient()
	if err != nil {
		log.Fatalf("Error creating Gitea client: %v", err)
	}

	version := os.Getenv("VERSION")
	if version == "" {
		log.Fatalf("VERSION environment variable is not set")
	}

	if err := updateVersionFile(version); err != nil {
		log.Fatalf("Error updating version file: %v", err)
	}

	repoOwner := "IDSolutions"
	repoName := "xpdb"

	release, err := createRelease(client, repoOwner, repoName, version)
	if err != nil {
		log.Fatalf("Error creating release: %v", err)
	}

	// Construct the filename using the version
	artifactFilename := fmt.Sprintf("xpdb-%s.zip", version)
	artifactPath := filepath.Join("releases", artifactFilename)

	if err := uploadArtifact(client, repoOwner, repoName, release.ID, artifactPath); err != nil {
		log.Fatalf("Error uploading release asset: %v", err)
	}

	fmt.Println("Release created, artifact uploaded, and version file updated successfully!")
}

func updateVersionFile(version string) error {
	versionInfo := VersionInfo{Version: version}
	jsonData, err := json.MarshalIndent(versionInfo, "", "  ")
	if err != nil {
		return fmt.Errorf("error marshaling version info: %w", err)
	}

	err = os.WriteFile("xpdb_version.json", jsonData, 0644)
	if err != nil {
		return fmt.Errorf("error writing version file: %w", err)
	}

	return nil
}

func createGiteaClient() (*gitea.Client, error) {
	token := os.Getenv("GITHUB_TOKEN")
	if token == "" {
		return nil, fmt.Errorf("GITHUB_TOKEN environment variable is not set")
	}
	return gitea.NewClient("https://gitea.innovativedevsolutions.org", gitea.SetToken(token))
}

func createRelease(client *gitea.Client, owner, repo, version string) (*gitea.Release, error) {
	release, _, err := client.CreateRelease(owner, repo, gitea.CreateReleaseOption{
		TagName: version,
		Title:   fmt.Sprintf("eXtended Persistent DB v%s", version),
		Note:    fmt.Sprintf("Release notes for version %s", version),
	})
	return release, err
}

func uploadArtifact(client *gitea.Client, owner, repo string, releaseID int64, artifactPath string) error {
	file, err := os.Open(artifactPath)
	if err != nil {
		return fmt.Errorf("error opening artifact file: %w", err)
	}
	defer file.Close()

	_, _, err = client.CreateReleaseAttachment(owner, repo, releaseID, file, filepath.Base(artifactPath))
	return err
}
