// Command foundation-check 执行公共基础迁移前后发布门禁。
package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"time"

	"github.com/bytedance/sonic"
	"go.uber.org/zap"

	"github.com/break/junhong_cmp_fiber/internal/infrastructure/releasegate"
	"github.com/break/junhong_cmp_fiber/pkg/config"
	"github.com/break/junhong_cmp_fiber/pkg/database"
)

func main() {
	phase := flag.String("phase", releasegate.PhasePre, "检查阶段：pre 或 post")
	timeout := flag.Duration("timeout", time.Minute, "检查超时时间")
	flag.Parse()

	if err := run(*phase, *timeout); err != nil {
		fmt.Fprintf(os.Stderr, "公共基础发布门禁失败：%v\n", err)
		os.Exit(1)
	}
}

func run(phase string, timeout time.Duration) error {
	cfg, err := config.Load()
	if err != nil {
		return fmt.Errorf("加载配置失败：%w", err)
	}
	db, err := database.InitPostgreSQL(&cfg.Database, zap.NewNop())
	if err != nil {
		return fmt.Errorf("连接 PostgreSQL 失败：%w", err)
	}
	if sqlDB, dbErr := db.DB(); dbErr == nil {
		defer func() { _ = sqlDB.Close() }()
	}
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()
	report, err := releasegate.NewChecker(db).Run(ctx, phase)
	if err != nil {
		return err
	}
	encoded, err := sonic.Marshal(report)
	if err != nil {
		return fmt.Errorf("序列化门禁报告失败：%w", err)
	}
	fmt.Println(string(encoded))
	if !report.Passed() {
		return fmt.Errorf("发现阻断项，请按稳定错误码处理后重试")
	}
	return nil
}
