package storage

import (
	"context"
	"errors"

	"github.com/jackc/pgx/v5"
	"github.com/nomadcode/nomadcode-core/internal/db"
)

var (
	ErrProjectSyncNotFound = errors.New("project sync setting not found")
)

// CreateProjectSyncRecord inserts a new project sync setting row as active.
// It expects normalized fields from the callers.
func (s *Store) CreateProjectSyncRecord(ctx context.Context, args db.CreateProjectSyncSettingParams) (db.ProjectSyncSetting, error) {
	return s.queries.CreateProjectSyncSetting(ctx, args)
}

// GetActiveProjectSyncSettingByTarget retrieves the active project sync config for a provider/project target.
func (s *Store) GetActiveProjectSyncSettingByTarget(ctx context.Context, provider string, tenant string, project string) (db.ProjectSyncSetting, error) {
	result, err := s.queries.GetActiveProjectSyncSettingByTarget(ctx, db.GetActiveProjectSyncSettingByTargetParams{
		Provider: provider,
		Tenant:   tenant,
		Project:  project,
	})
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			return db.ProjectSyncSetting{}, ErrProjectSyncNotFound
		}
		return db.ProjectSyncSetting{}, err
	}
	return result, nil
}

// DeactivateProjectSyncSetting marks the active config for a target as inactive.
func (s *Store) DeactivateProjectSyncSetting(ctx context.Context, provider string, tenant string, project string) (db.ProjectSyncSetting, error) {
	return s.queries.DeactivateProjectSyncSetting(ctx, db.DeactivateProjectSyncSettingParams{
		Provider: provider,
		Tenant:   tenant,
		Project:  project,
	})
}
