package sqlite

import (
	"context"

	"chat-switchboard/models"
	"chat-switchboard/store"
)

type CapOverrideStore struct{}

func NewCapOverrideStore() *CapOverrideStore { return &CapOverrideStore{} }

func (s *CapOverrideStore) Set(ctx context.Context, o *models.CapabilityOverride) error {
	id := store.NewID()
	_, err := DB.ExecContext(ctx, `
		INSERT INTO capability_overrides (id, provider_config_id, model_id, field, value, set_by)
		VALUES (?, ?, ?, ?, ?, ?)
		ON CONFLICT (provider_config_id, model_id, field) DO UPDATE SET
			value = excluded.value,
			set_by = excluded.set_by,
			created_at = datetime('now')
	`, id, o.ProviderConfigID, o.ModelID, o.Field, o.Value, o.SetBy)
	return err
}

func (s *CapOverrideStore) Delete(ctx context.Context, id string) error {
	_, err := DB.ExecContext(ctx, `DELETE FROM capability_overrides WHERE id = ?`, id)
	return err
}

func (s *CapOverrideStore) ListForModel(ctx context.Context, modelID string) ([]models.CapabilityOverride, error) {
	return s.query(ctx, `
		SELECT id, provider_config_id, model_id, field, value, set_by, created_at
		FROM capability_overrides
		WHERE model_id = ?
		ORDER BY provider_config_id, field
	`, modelID)
}

func (s *CapOverrideStore) ListForProviderModel(ctx context.Context, providerConfigID, modelID string) ([]models.CapabilityOverride, error) {
	return s.query(ctx, `
		SELECT id, provider_config_id, model_id, field, value, set_by, created_at
		FROM capability_overrides
		WHERE model_id = ? AND (provider_config_id = ? OR provider_config_id IS NULL)
		ORDER BY provider_config_id, field
	`, modelID, providerConfigID)
}

func (s *CapOverrideStore) ListAll(ctx context.Context) ([]models.CapabilityOverride, error) {
	return s.query(ctx, `
		SELECT id, provider_config_id, model_id, field, value, set_by, created_at
		FROM capability_overrides
		ORDER BY model_id, provider_config_id, field
	`)
}

func (s *CapOverrideStore) DeleteForProvider(ctx context.Context, providerConfigID string) error {
	_, err := DB.ExecContext(ctx, `
		DELETE FROM capability_overrides WHERE provider_config_id = ?
	`, providerConfigID)
	return err
}

func (s *CapOverrideStore) query(ctx context.Context, q string, args ...interface{}) ([]models.CapabilityOverride, error) {
	rows, err := DB.QueryContext(ctx, q, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var result []models.CapabilityOverride
	for rows.Next() {
		var o models.CapabilityOverride
		if err := rows.Scan(&o.ID, &o.ProviderConfigID, &o.ModelID, &o.Field, &o.Value, &o.SetBy, &o.CreatedAt); err != nil {
			return nil, err
		}
		result = append(result, o)
	}
	return result, rows.Err()
}

// ensure interface compliance (compile-time check)
var _ store.CapabilityOverrideStore = (*CapOverrideStore)(nil)

// also check the health store interface at this package level
// (health.Store is in the health package, but we verify via the sql.Rows pattern)
func init() {
	// compile-time interface checks happen via the var _ lines above
}
