// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package integration

import (
	"bytes"
	"crypto/md5"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"mime/multipart"
	"net/http"
	"strings"
	"testing"

	"forgejo.org/models/db"
	"forgejo.org/models/packages"
	"forgejo.org/models/unittest"
	user_model "forgejo.org/models/user"
	"forgejo.org/modules/packages/rubygems"
	"forgejo.org/tests"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestPackageRubyGems(t *testing.T) {
	defer tests.PrepareTestEnv(t)()

	user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})

	packageName := "gitea"
	packageVersion := "1.0.5"
	packageFilename := "gitea-1.0.5.gem"
	packageDependency := "runtime-dep:>= 1.2.0&< 2.0"
	rubyRequirements := "ruby:>= 2.3.0"
	sep := "---"

	gemContent, _ := base64.StdEncoding.DecodeString(`bWV0YWRhdGEuZ3oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
[encoded data, 6083 characters]
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`)
	checksum := fmt.Sprintf("%x", sha256.Sum256(gemContent))

	holaPackageName := "hola"
	holaPackageVersion := "0.0.1"
	// holaPackageFilename := "hola-0.0.1.gem"
	holaPackageDependency := "example:~> 1.1&>= 1.1.4,zero:>= 0"
	holaRubyGemsRequirements := "rubygems:= 1.2.3"
	// sep := "---"

	holaGemContent, _ := base64.StdEncoding.DecodeString(`bWV0YWRhdGEuZ3oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
[encoded data, 5390 characters]
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==`)
	holaChecksum := fmt.Sprintf("%x", sha256.Sum256(holaGemContent))

	binaryPackageName := "debug_inspector"
	binaryPackageVersion := "0.0.3"
	binaryRubyGemsRequirements := "ruby:~> 3.1.0"
	binaryGemContent, _ := base64.StdEncoding.DecodeString(`bWV0YWRhdGEuZ3oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
[encoded data, 9548 characters]
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==`)
	binaryChecksum := fmt.Sprintf("%x", sha256.Sum256(binaryGemContent))

	root := fmt.Sprintf("/api/packages/%s/rubygems", user.Name)

	uploadFile := func(t *testing.T, content []byte, expectedStatus int) {
		req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/api/v1/gems", root), bytes.NewReader(content)).
			AddBasicAuth(user.Name)
		MakeRequest(t, req, expectedStatus)
	}

	t.Run("Upload", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		uploadFile(t, gemContent, http.StatusCreated)

		pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems)
		require.NoError(t, err)
		assert.Len(t, pvs, 1)

		pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0])
		require.NoError(t, err)
		assert.NotNil(t, pd.SemVer)
		assert.IsType(t, &rubygems.Metadata{}, pd.Metadata)
		assert.Equal(t, packageName, pd.Package.Name)
		assert.Equal(t, packageVersion, pd.Version.Version)

		pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID)
		require.NoError(t, err)
		assert.Len(t, pfs, 1)
		assert.Equal(t, packageFilename, pfs[0].Name)
		assert.True(t, pfs[0].IsLead)

		pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID)
		require.NoError(t, err)
		assert.Equal(t, int64(4608), pb.Size)

		assert.Equal(t, "ruby", pd.Metadata.(*rubygems.Metadata).Platform)
	})

	t.Run("UploadBadRequest", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/api/v1/gems", root), bytes.NewReader(gemContent)).
			AddBasicAuth(user.Name).
			SetHeader("content-type", "multipart/form-data")
		MakeRequest(t, req, http.StatusBadRequest)
	})

	t.Run("UploadExists", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		uploadFile(t, gemContent, http.StatusConflict)
	})

	t.Run("Download", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		req := NewRequest(t, "GET", fmt.Sprintf("%s/gems/%s", root, packageFilename)).
			AddBasicAuth(user.Name)
		resp := MakeRequest(t, req, http.StatusOK)

		assert.Equal(t, gemContent, resp.Body.Bytes())

		pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems)
		require.NoError(t, err)
		assert.Len(t, pvs, 1)
		assert.Equal(t, int64(1), pvs[0].DownloadCount)
	})

	t.Run("DownloadGemspec", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		req := NewRequest(t, "GET", fmt.Sprintf("%s/quick/Marshal.4.8/%sspec.rz", root, packageFilename)).
			AddBasicAuth(user.Name)
		resp := MakeRequest(t, req, http.StatusOK)

		b, _ := base64.StdEncoding.DecodeString(`eJxi4Si1EndPzbWyCi5ITc5My0xOLMnMz2M8zMIRLeGpxGWsZ6RnzGbF5hqSyempxJWeWZKayGbN
EBJqJQjWFZZaVJyZnxfN5qnEZahnoGcKkjTwVBJyB6lUKEhMzk5MTwULGngqcRaVJlWCONEMBp5K
DGAWSKc7zFhPJamg0qRK99TcYphehZLU4hKInFhGSUlBsZW+PtgZepn5+iDxECRzDUDGcfh6hoA4
gAAAAP//MS06Gw==`)
		assert.Equal(t, b, resp.Body.Bytes())

		pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems)
		require.NoError(t, err)
		assert.Len(t, pvs, 1)
		assert.Equal(t, int64(1), pvs[0].DownloadCount)
	})

	t.Run("EnumeratePackages", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		enumeratePackages := func(t *testing.T, endpoint string, expectedContent []byte) {
			req := NewRequest(t, "GET", fmt.Sprintf("%s/%s", root, endpoint)).
				AddBasicAuth(user.Name)
			resp := MakeRequest(t, req, http.StatusOK)

			assert.Equal(t, expectedContent, resp.Body.Bytes())
		}

		b, _ := base64.StdEncoding.DecodeString(`H4sICAAAAAAA/3NwZWNzLjQuOABi4Yhmi+bwVOJKzyxJTWSzYnMNCbUSdE/NtbIKSy0qzszPi2bzVOIy1DPQM2WzZgjxVOIsKk2qBDEBAQAA///xOEYKOwAAAA==`)
		enumeratePackages(t, "specs.4.8.gz", b)
		b, _ = base64.StdEncoding.DecodeString(`H4sICAAAAAAA/2xhdGVzdF9zcGVjcy40LjgAYuGIZovm8FTiSs8sSU1ks2JzDQm1EnRPzbWyCkstKs7Mz4tm81TiMtQz0DNls2YI8VTiLCpNqgQxAQEAAP//8ThGCjsAAAA=`)
		enumeratePackages(t, "latest_specs.4.8.gz", b)
		b, _ = base64.StdEncoding.DecodeString(`H4sICAAAAAAA/3ByZXJlbGVhc2Vfc3BlY3MuNC44AGLhiGYABAAA//9snXr5BAAAAA==`)
		enumeratePackages(t, "prerelease_specs.4.8.gz", b)
	})

	t.Run("UploadHola", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		uploadFile(t, holaGemContent, http.StatusCreated)
	})

	t.Run("PackageInfo", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		req := NewRequest(t, "GET", fmt.Sprintf("%s/info/%s", root, packageName)).
			AddBasicAuth(user.Name)
		resp := MakeRequest(t, req, http.StatusOK)
		expected := fmt.Sprintf("%s\n%s %s|checksum:%s,%s\n",
			sep, packageVersion, packageDependency, checksum, rubyRequirements)
		assert.Equal(t, expected, resp.Body.String())
	})

	t.Run("HolaPackageInfo", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		req := NewRequest(t, "GET", fmt.Sprintf("%s/info/%s", root, holaPackageName)).
			AddBasicAuth(user.Name)
		resp := MakeRequest(t, req, http.StatusOK)
		expected := fmt.Sprintf("%s\n%s %s|checksum:%s,%s\n",
			sep, holaPackageVersion, holaPackageDependency, holaChecksum, holaRubyGemsRequirements)
		assert.Equal(t, expected, resp.Body.String())
	})

	t.Run("UploadBinary", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		uploadFile(t, binaryGemContent, http.StatusCreated)

		pvs, err := packages.GetVersionsByPackageName(db.DefaultContext, user.ID, packages.TypeRubyGems, binaryPackageName)
		require.NoError(t, err)

		pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0])
		require.NoError(t, err)

		assert.Equal(t, binaryPackageName, pd.Package.Name)
		assert.Equal(t, "x86_64-linux-musl", pd.Metadata.(*rubygems.Metadata).Platform)
	})

	t.Run("BinaryPackageInfo", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		req := NewRequest(t, "GET", fmt.Sprintf("%s/info/%s", root, binaryPackageName)).
			AddBasicAuth(user.Name)
		resp := MakeRequest(t, req, http.StatusOK)
		expected := fmt.Sprintf("%s\n%s-x86_64-linux-musl |checksum:%s,%s\n",
			sep, binaryPackageVersion, binaryChecksum, binaryRubyGemsRequirements)
		assert.Equal(t, expected, resp.Body.String())
	})

	t.Run("Versions", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		versionsReq := NewRequest(t, "GET", fmt.Sprintf("%s/versions", root)).
			AddBasicAuth(user.Name)
		versionsResp := MakeRequest(t, versionsReq, http.StatusOK)
		infoReq := NewRequest(t, "GET", fmt.Sprintf("%s/info/%s", root, packageName)).
			AddBasicAuth(user.Name)
		infoResp := MakeRequest(t, infoReq, http.StatusOK)
		holaInfoReq := NewRequest(t, "GET", fmt.Sprintf("%s/info/%s", root, holaPackageName)).
			AddBasicAuth(user.Name)
		holaInfoResp := MakeRequest(t, holaInfoReq, http.StatusOK)
		binaryInfoReq := NewRequest(t, "GET", fmt.Sprintf("%s/info/%s", root, binaryPackageName)).
			AddBasicAuth(user.Name)
		binaryInfoResp := MakeRequest(t, binaryInfoReq, http.StatusOK)

		// expected := fmt.Sprintf("%s\n%s %s %x\n",
		// 	sep, packageName, packageVersion, md5.Sum(infoResp.Body.Bytes()))
		lines := versionsResp.Body.String()
		assert.ElementsMatch(t, strings.Split(lines, "\n"), []string{
			sep,
			fmt.Sprintf("%s %s_x86_64-linux-musl %x", binaryPackageName, binaryPackageVersion, md5.Sum(binaryInfoResp.Body.Bytes())),
			fmt.Sprintf("%s %s %x", packageName, packageVersion, md5.Sum(infoResp.Body.Bytes())),
			fmt.Sprintf("%s %s %x", holaPackageName, holaPackageVersion, md5.Sum(holaInfoResp.Body.Bytes())),
			"",
		})
	})

	t.Run("DeleteHola", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		body := bytes.Buffer{}
		writer := multipart.NewWriter(&body)
		writer.WriteField("gem_name", holaPackageName)
		writer.WriteField("version", holaPackageVersion)
		writer.Close()

		req := NewRequestWithBody(t, "DELETE", fmt.Sprintf("%s/api/v1/gems/yank", root), &body).
			SetHeader("Content-Type", writer.FormDataContentType()).
			AddBasicAuth(user.Name)
		MakeRequest(t, req, http.StatusOK)
	})

	t.Run("DeleteBinary", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		body := bytes.Buffer{}
		writer := multipart.NewWriter(&body)
		writer.WriteField("gem_name", binaryPackageName)
		writer.WriteField("version", binaryPackageVersion)
		writer.Close()

		req := NewRequestWithBody(t, "DELETE", fmt.Sprintf("%s/api/v1/gems/yank", root), &body).
			SetHeader("Content-Type", writer.FormDataContentType()).
			AddBasicAuth(user.Name)
		MakeRequest(t, req, http.StatusOK)
	})

	t.Run("Delete", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		body := bytes.Buffer{}
		writer := multipart.NewWriter(&body)
		writer.WriteField("gem_name", packageName)
		writer.WriteField("version", packageVersion)
		writer.Close()

		req := NewRequestWithBody(t, "DELETE", fmt.Sprintf("%s/api/v1/gems/yank", root), &body).
			SetHeader("Content-Type", writer.FormDataContentType()).
			AddBasicAuth(user.Name)
		MakeRequest(t, req, http.StatusOK)

		pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems)
		require.NoError(t, err)
		assert.Empty(t, pvs)
	})

	t.Run("NonExistingGem", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		req := NewRequest(t, "GET", fmt.Sprintf("%s/info/%s", root, packageName)).
			AddBasicAuth(user.Name)
		_ = MakeRequest(t, req, http.StatusNotFound)
	})
	t.Run("EmptyVersions", func(t *testing.T) {
		defer tests.PrintCurrentTest(t)()

		req := NewRequest(t, "GET", fmt.Sprintf("%s/versions", root)).
			AddBasicAuth(user.Name)
		resp := MakeRequest(t, req, http.StatusOK)
		assert.Equal(t, sep+"\n", resp.Body.String())
	})
}
