package worker

import (
	"context"
	"database/sql"

	"deployment-manager/internal/db"
	"deployment-manager/internal/events"
	"deployment-manager/internal/k8s"
	"deployment-manager/internal/model"
)

type DeploymentManager struct {
	repoStore *db.RepoStore
	kubectl   *k8s.KubectlClient
	eventChan chan<- *events.Event
}

func NewDeploymentManager(database *sql.DB, eventChan chan<- *events.Event) *DeploymentManager {
	return &DeploymentManager{
		repoStore: db.NewRepoStore(database),
		kubectl:   k8s.NewKubectlClient("default"),
		eventChan: eventChan,
	}
}

func (dm *DeploymentManager) StopDeployment(ctx context.Context, repoID int64) error {
	repo, err := dm.repoStore.Get(repoID)
	if err != nil {
		return err
	}
	
	appName := k8s.GetAppName(repo)
	
	// Scale deployment to 0
	if err := dm.kubectl.ScaleDeployment(ctx, dm.eventChan, repoID, appName, 0); err != nil {
		return err
	}
	
	// Update status
	repo.Status = model.StatusStopped
	if err := dm.repoStore.Update(repo); err != nil {
		return err
	}
	
	// Send event
	dm.eventChan <- events.NewRepoEvent(repo, events.EventTypeRepoUpdated)
	
	return nil
}

func (dm *DeploymentManager) RestartDeployment(ctx context.Context, repoID int64) error {
	repo, err := dm.repoStore.Get(repoID)
	if err != nil {
		return err
	}
	
	appName := k8s.GetAppName(repo)
	
	// Update status to restarting
	repo.Status = model.StatusRestarting
	if err := dm.repoStore.Update(repo); err != nil {
		return err
	}
	
	// Scale deployment to 1
	if err := dm.kubectl.ScaleDeployment(ctx, dm.eventChan, repoID, appName, 1); err != nil {
		return err
	}
	
	// Update status to deployed
	repo.Status = model.StatusDeployed
	if err := dm.repoStore.Update(repo); err != nil {
		return err
	}
	
	// Send event
	dm.eventChan <- events.NewRepoEvent(repo, events.EventTypeRepoUpdated)
	
	return nil
}

func (dm *DeploymentManager) DeleteDeployment(ctx context.Context, repoID int64) error {
	repo, err := dm.repoStore.Get(repoID)
	if err != nil {
		return err
	}
	
	appName := k8s.GetAppName(repo)
	
	// Delete Kubernetes resources
	if err := dm.kubectl.DeleteResources(ctx, dm.eventChan, repoID, appName); err != nil {
		return err
	}
	
	// Update status to deleted
	repo.Status = model.StatusDeleted
	if err := dm.repoStore.Update(repo); err != nil {
		return err
	}
	
	// Send event
	dm.eventChan <- events.NewRepoEvent(repo, events.EventTypeRepoDeleted)
	
	return nil
}
