package mongo

import (
	"context"
	"errors"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	mongodriver "go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"

	"scheduler-backend/internal/store/model"
)

type SystemConfigStore struct {
	collection *mongodriver.Collection
}

func NewSystemConfigStore(db *mongodriver.Database) *SystemConfigStore {
	return &SystemConfigStore{
		collection: db.Collection("system_configs"),
	}
}

func (s *SystemConfigStore) List(ctx context.Context) ([]model.SystemConfig, error) {
	findCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	cursor, err := s.collection.Find(findCtx, bson.D{}, options.Find().SetSort(bson.D{{Key: "updatedAt", Value: -1}}))
	if err != nil {
		return nil, err
	}
	defer cursor.Close(findCtx)

	items := make([]model.SystemConfig, 0)
	for cursor.Next(findCtx) {
		var item model.SystemConfig
		if err := cursor.Decode(&item); err != nil {
			return nil, err
		}
		items = append(items, item)
	}
	if err := cursor.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

func (s *SystemConfigStore) GetByID(ctx context.Context, id primitive.ObjectID) (*model.SystemConfig, error) {
	findCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	var item model.SystemConfig
	err := s.collection.FindOne(findCtx, bson.M{"_id": id}).Decode(&item)
	if err != nil {
		if errors.Is(err, mongodriver.ErrNoDocuments) {
			return nil, nil
		}
		return nil, err
	}
	return &item, nil
}

func (s *SystemConfigStore) Create(ctx context.Context, item *model.SystemConfig) error {
	insertCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	now := time.Now()
	item.CreatedAt = now
	item.UpdatedAt = now

	result, err := s.collection.InsertOne(insertCtx, item)
	if err != nil {
		return err
	}
	if oid, ok := result.InsertedID.(primitive.ObjectID); ok {
		item.ID = oid
	}
	return nil
}

func (s *SystemConfigStore) Update(ctx context.Context, item *model.SystemConfig) error {
	updateCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	item.UpdatedAt = time.Now()
	_, err := s.collection.UpdateByID(updateCtx, item.ID, bson.M{
		"$set": bson.M{
			"key":         item.Key,
			"title":       item.Title,
			"value":       item.Value,
			"valueType":   item.ValueType,
			"description": item.Description,
			"enabled":     item.Enabled,
			"updatedAt":   item.UpdatedAt,
		},
	})
	return err
}

func (s *SystemConfigStore) ToggleEnabled(ctx context.Context, id primitive.ObjectID, enabled bool) error {
	updateCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	_, err := s.collection.UpdateByID(updateCtx, id, bson.M{
		"$set": bson.M{
			"enabled":   enabled,
			"updatedAt": time.Now(),
		},
	})
	return err
}
