package businessscope

import (
	"context"
	"errors"
	"regexp"
	"testing"
	"time"

	"github.com/DATA-DOG/go-sqlmock"
)

const scopeInsertSQL = `INSERT INTO business_customer_vehicle_scope(
source_version,customer_id,vin,vehicle_id,contract_id,contract_code,plate_number,project_name,operation_status,scope_start_at,source_updated_at,published_at
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`

func publishSnapshot(version string) Snapshot {
	generatedAt := time.Date(2026, 7, 14, 8, 0, 0, 0, time.UTC)
	return Snapshot{
		RunID: "0123456789abcdef0123456789abcdef", SourceVersion: version,
		Checksum:    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
		GeneratedAt: generatedAt, Candidates: 1,
		Items: []ScopeItem{{
			VehicleID: 10, VIN: "LVIN0001", PlateNumber: "沪A00001", CustomerID: 100,
			ContractID: 1010, ContractCode: "HT-1", ProjectName: "项目", OperationStatus: "1",
			ScopeStartAt: generatedAt.Add(-time.Hour),
		}},
	}
}

func TestPublishRebuildsPreviouslyStoredVersionBeforeActivation(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()
	snapshot := publishSnapshot("oneos-v1:new")

	mock.ExpectBegin()
	mock.ExpectQuery(regexp.QuoteMeta(`SELECT active_version FROM business_scope_state WHERE id=1 FOR UPDATE`)).
		WillReturnRows(sqlmock.NewRows([]string{"active_version"}).AddRow("oneos-v1:current"))
	mock.ExpectExec(`INSERT INTO business_scope_sync_run`).
		WithArgs(snapshot.RunID, SourceSystem, snapshot.SourceVersion, "published", 1, 1, 0, snapshot.Checksum, snapshot.GeneratedAt, sqlmock.AnyArg()).
		WillReturnResult(sqlmock.NewResult(1, 1))
	mock.ExpectExec(regexp.QuoteMeta(`DELETE FROM business_customer_vehicle_scope WHERE source_version=?`)).
		WithArgs(snapshot.SourceVersion).WillReturnResult(sqlmock.NewResult(0, 1))
	prepared := mock.ExpectPrepare(regexp.QuoteMeta(scopeInsertSQL))
	item := snapshot.Items[0]
	prepared.ExpectExec().WithArgs(
		snapshot.SourceVersion, item.CustomerID, item.VIN, item.VehicleID, item.ContractID,
		item.ContractCode, item.PlateNumber, item.ProjectName, item.OperationStatus, item.ScopeStartAt, nil, sqlmock.AnyArg(),
	).WillReturnResult(sqlmock.NewResult(1, 1))
	mock.ExpectExec(`UPDATE business_scope_state SET`).
		WithArgs(snapshot.SourceVersion, snapshot.Checksum, 1, 1, 0, snapshot.GeneratedAt, sqlmock.AnyArg(), sqlmock.AnyArg()).
		WillReturnResult(sqlmock.NewResult(0, 1))
	mock.ExpectCommit()

	result, err := Publish(context.Background(), db, snapshot)
	if err != nil {
		t.Fatal(err)
	}
	if !result.Changed || result.ActiveVersion != snapshot.SourceVersion {
		t.Fatalf("unexpected publish result: %#v", result)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatal(err)
	}
}

func TestPublishUnchangedDoesNotRewriteScopeRows(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()
	snapshot := publishSnapshot("oneos-v1:same")

	mock.ExpectBegin()
	mock.ExpectQuery(regexp.QuoteMeta(`SELECT active_version FROM business_scope_state WHERE id=1 FOR UPDATE`)).
		WillReturnRows(sqlmock.NewRows([]string{"active_version"}).AddRow(snapshot.SourceVersion))
	mock.ExpectExec(`INSERT INTO business_scope_sync_run`).
		WithArgs(snapshot.RunID, SourceSystem, snapshot.SourceVersion, "unchanged", 1, 1, 0, snapshot.Checksum, snapshot.GeneratedAt, sqlmock.AnyArg()).
		WillReturnResult(sqlmock.NewResult(1, 1))
	mock.ExpectExec(`UPDATE business_scope_state SET`).
		WithArgs(snapshot.SourceVersion, snapshot.Checksum, 1, 1, 0, snapshot.GeneratedAt, sqlmock.AnyArg(), sqlmock.AnyArg()).
		WillReturnResult(sqlmock.NewResult(0, 1))
	mock.ExpectCommit()

	result, err := Publish(context.Background(), db, snapshot)
	if err != nil {
		t.Fatal(err)
	}
	if result.Changed {
		t.Fatalf("unchanged snapshot reported as changed: %#v", result)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatal(err)
	}
}

func TestPublishRollsBackWhenVersionCannotBeCleared(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()
	snapshot := publishSnapshot("oneos-v1:new")

	mock.ExpectBegin()
	mock.ExpectQuery(regexp.QuoteMeta(`SELECT active_version FROM business_scope_state WHERE id=1 FOR UPDATE`)).
		WillReturnRows(sqlmock.NewRows([]string{"active_version"}).AddRow("oneos-v1:current"))
	mock.ExpectExec(`INSERT INTO business_scope_sync_run`).WillReturnResult(sqlmock.NewResult(1, 1))
	mock.ExpectExec(regexp.QuoteMeta(`DELETE FROM business_customer_vehicle_scope WHERE source_version=?`)).
		WithArgs(snapshot.SourceVersion).WillReturnError(errors.New("delete failed"))
	mock.ExpectRollback()

	if _, err := Publish(context.Background(), db, snapshot); err == nil {
		t.Fatal("publish should fail when stale version cannot be rebuilt")
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatal(err)
	}
}
