package repository

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/model/crm_contact/domain/entity"
	domrepo "haixun-backend/internal/model/crm_contact/domain/repository"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type mongoRepository struct {
	collection *mongo.Collection
}

func NewMongoRepository(db *mongo.Database) domrepo.Repository {
	if db == nil {
		return &mongoRepository{}
	}
	return &mongoRepository{collection: db.Collection(entity.CollectionName)}
}

func baseFilter(tenantID, ownerUID string) bson.M {
	return bson.M{
		"tenant_id": strings.TrimSpace(tenantID),
		"owner_uid": strings.TrimSpace(ownerUID),
	}
}

func (r *mongoRepository) EnsureIndexes(ctx context.Context) error {
	if r.collection == nil {
		return nil
	}
	_, err := r.collection.Indexes().CreateMany(ctx, []mongo.IndexModel{
		{
			Keys: bson.D{
				{Key: "tenant_id", Value: 1},
				{Key: "owner_uid", Value: 1},
				{Key: "brand_id", Value: 1},
				{Key: "create_at", Value: -1},
			},
		},
		{
			Keys: bson.D{
				{Key: "tenant_id", Value: 1},
				{Key: "owner_uid", Value: 1},
				{Key: "author_id", Value: 1},
			},
			Options: options.Index().SetUnique(true),
		},
	})
	return err
}

func (r *mongoRepository) Create(ctx context.Context, contact *entity.CRMContact) error {
	if r.collection == nil {
		return app.For(code.Persona).DBUnavailable("Mongo is not configured")
	}
	if contact == nil {
		return app.For(code.Persona).InputMissingRequired("contact is required")
	}
	_, err := r.collection.InsertOne(ctx, contact)
	return err
}

func (r *mongoRepository) Get(ctx context.Context, tenantID, ownerUID, contactID string) (*entity.CRMContact, error) {
	if r.collection == nil {
		return nil, app.For(code.Persona).DBUnavailable("Mongo is not configured")
	}
	contactID = strings.TrimSpace(contactID)
	if contactID == "" {
		return nil, app.For(code.Persona).InputMissingRequired("contact_id is required")
	}
	filter := baseFilter(tenantID, ownerUID)
	filter["_id"] = contactID
	var out entity.CRMContact
	err := r.collection.FindOne(ctx, filter).Decode(&out)
	if err != nil {
		if err == mongo.ErrNoDocuments {
			return nil, app.For(code.Persona).ResNotFound("crm contact not found")
		}
		return nil, err
	}
	return &out, nil
}

func (r *mongoRepository) GetByAuthor(ctx context.Context, tenantID, ownerUID, authorID string) (*entity.CRMContact, error) {
	if r.collection == nil {
		return nil, app.For(code.Persona).DBUnavailable("Mongo is not configured")
	}
	authorID = strings.TrimSpace(authorID)
	if authorID == "" {
		return nil, app.For(code.Persona).InputMissingRequired("author_id is required")
	}
	filter := baseFilter(tenantID, ownerUID)
	filter["author_id"] = authorID
	var out entity.CRMContact
	err := r.collection.FindOne(ctx, filter).Decode(&out)
	if err != nil {
		if err == mongo.ErrNoDocuments {
			return nil, app.For(code.Persona).ResNotFound("crm contact not found")
		}
		return nil, err
	}
	return &out, nil
}

func (r *mongoRepository) Update(ctx context.Context, tenantID, ownerUID, contactID string, patch map[string]interface{}) (*entity.CRMContact, error) {
	if r.collection == nil {
		return nil, app.For(code.Persona).DBUnavailable("Mongo is not configured")
	}
	if len(patch) == 0 {
		return nil, app.For(code.Persona).InputMissingRequired("patch is required")
	}
	contactID = strings.TrimSpace(contactID)
	filter := baseFilter(tenantID, ownerUID)
	filter["_id"] = contactID
	opts := options.FindOneAndUpdate().SetReturnDocument(options.After)
	var out entity.CRMContact
	err := r.collection.FindOneAndUpdate(ctx, filter, bson.M{"$set": patch}, opts).Decode(&out)
	if err != nil {
		if err == mongo.ErrNoDocuments {
			return nil, app.For(code.Persona).ResNotFound("crm contact not found")
		}
		return nil, err
	}
	return &out, nil
}

func (r *mongoRepository) Delete(ctx context.Context, tenantID, ownerUID, contactID string) error {
	if r.collection == nil {
		return app.For(code.Persona).DBUnavailable("Mongo is not configured")
	}
	contactID = strings.TrimSpace(contactID)
	if contactID == "" {
		return app.For(code.Persona).InputMissingRequired("contact_id is required")
	}
	filter := baseFilter(tenantID, ownerUID)
	filter["_id"] = contactID
	_, err := r.collection.DeleteOne(ctx, filter)
	return err
}

func (r *mongoRepository) List(ctx context.Context, tenantID, ownerUID string, filter domrepo.ListFilter) ([]entity.CRMContact, int, error) {
	if r.collection == nil {
		return nil, 0, app.For(code.Persona).DBUnavailable("Mongo is not configured")
	}
	query := baseFilter(tenantID, ownerUID)
	if filter.BrandID != "" {
		query["brand_id"] = filter.BrandID
	}
	if filter.Status != "" {
		query["status"] = filter.Status
	}
	if filter.Tag != "" {
		query["tags"] = filter.Tag
	}

	limit := filter.Limit
	if limit <= 0 {
		limit = 20
	}
	if limit > 100 {
		limit = 100
	}
	skip := filter.Offset
	if skip < 0 {
		skip = 0
	}

	total, err := r.collection.CountDocuments(ctx, query)
	if err != nil {
		return nil, 0, err
	}

	opts := options.Find().
		SetSort(bson.D{{Key: "create_at", Value: -1}}).
		SetSkip(int64(skip)).
		SetLimit(int64(limit))
	cur, err := r.collection.Find(ctx, query, opts)
	if err != nil {
		return nil, 0, err
	}
	defer cur.Close(ctx)

	var out []entity.CRMContact
	if err := cur.All(ctx, &out); err != nil {
		return nil, 0, err
	}
	return out, int(total), nil
}

func (r *mongoRepository) UpsertByAuthor(ctx context.Context, contact *entity.CRMContact) (*entity.CRMContact, error) {
	if r.collection == nil {
		return nil, app.For(code.Persona).DBUnavailable("Mongo is not configured")
	}
	if contact == nil {
		return nil, app.For(code.Persona).InputMissingRequired("contact is required")
	}
	filter := baseFilter(contact.TenantID, contact.OwnerUID)
	filter["author_id"] = contact.AuthorID
	update := bson.M{"$set": contact}
	opts := options.FindOneAndUpdate().
		SetUpsert(true).
		SetReturnDocument(options.After)
	var out entity.CRMContact
	err := r.collection.FindOneAndUpdate(ctx, filter, update, opts).Decode(&out)
	if err != nil {
		return nil, err
	}
	return &out, nil
}
