package report

import (
	"path/filepath"
	"testing"
)

func TestMergeCSVDeployThenSubmit(t *testing.T) {
	path := filepath.Join(t.TempDir(), "deploy-submit.csv")

	deployRows := []FolderRow{
		{Bucket: "b1", Foldering: "folder_1", Name: "N1", Source: "S1", Files: 10, URL: "https://b1/", Upload: "YES", DeployStatus: "SUCCESS", Duration: "1.2"},
		{Bucket: "b2", Foldering: "folder_2", Name: "N2", Source: "S2", DeployStatus: "FAILED", DeployError: "boom"},
	}
	if err := MergeCSV(path, StageDeploy, deployRows); err != nil {
		t.Fatal(err)
	}

	submitRows := []FolderRow{
		{Bucket: "b1", Foldering: "folder_1", Source: "S1", SubmitStatus: "SUCCESS", URLCount: 42},
		{Bucket: "b2", Foldering: "folder_2", Source: "S2", SubmitStatus: "FAILED", SubmitNotes: "indexnow 500"},
	}
	if err := MergeCSV(path, StageSubmit, submitRows); err != nil {
		t.Fatal(err)
	}

	rows, err := readCSV(path)
	if err != nil {
		t.Fatal(err)
	}
	if len(rows) != 2 {
		t.Fatalf("rows = %d, want 2 (deploy+submit merged, not appended)", len(rows))
	}
	r1 := rows[0]
	if r1.Foldering != "folder_1" || r1.Bucket != "b1" || r1.Name != "N1" {
		t.Errorf("identity lost after merge: %+v", r1)
	}
	if r1.DeployStatus != "SUCCESS" || r1.Upload != "YES" || r1.Files != 10 {
		t.Errorf("deploy half lost after submit merge: %+v", r1)
	}
	if r1.SubmitStatus != "SUCCESS" || r1.URLCount != 42 {
		t.Errorf("submit half not filled: %+v", r1)
	}
	r2 := rows[1]
	if r2.DeployStatus != "FAILED" || r2.DeployError != "boom" {
		t.Errorf("deploy half of failed row lost: %+v", r2)
	}
	if r2.SubmitStatus != "FAILED" || r2.SubmitNotes != "indexnow 500" {
		t.Errorf("submit half of failed row not filled: %+v", r2)
	}
}

func TestMergeCSVRerunReplacesStageColumns(t *testing.T) {
	path := filepath.Join(t.TempDir(), "deploy-submit.csv")

	first := []FolderRow{{Bucket: "b1", Foldering: "folder_1", DeployStatus: "FAILED", DeployError: "boom"}}
	if err := MergeCSV(path, StageDeploy, first); err != nil {
		t.Fatal(err)
	}
	second := []FolderRow{{Bucket: "b1", Foldering: "folder_1", DeployStatus: "SUCCESS", Upload: "YES"}}
	if err := MergeCSV(path, StageDeploy, second); err != nil {
		t.Fatal(err)
	}

	rows, err := readCSV(path)
	if err != nil {
		t.Fatal(err)
	}
	if len(rows) != 1 {
		t.Fatalf("rows = %d, want 1 after rerun upsert", len(rows))
	}
	if rows[0].DeployStatus != "SUCCESS" || rows[0].DeployError != "" {
		t.Errorf("stale deploy columns survived rerun: %+v", rows[0])
	}
}
