package repository

import (
	"context"
	"encoding/json"
	"eslogad-be/internal/contract"
	"eslogad-be/internal/entities"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

type AppSettingRepository struct{ db *gorm.DB }

func NewAppSettingRepository(db *gorm.DB) *AppSettingRepository {
	return &AppSettingRepository{
		db: db,
	}
}

func (r *AppSettingRepository) Get(ctx context.Context, key string) (*entities.AppSetting, error) {
	db := DBFromContext(ctx, r.db)
	var e entities.AppSetting
	if err := db.WithContext(ctx).First(&e, "key = ?", key).Error; err != nil {
		return nil, err
	}
	return &e, nil
}
func (r *AppSettingRepository) Upsert(ctx context.Context, key string, value entities.JSONB) error {
	db := DBFromContext(ctx, r.db)
	return db.WithContext(ctx).Exec("INSERT INTO app_settings(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = EXCLUDED.value, updated_at = CURRENT_TIMESTAMP", key, value).Error
}

func (r *AppSettingRepository) GetDepartmentRecipients(ctx context.Context) ([]uuid.UUID, error) {
	setting, err := r.Get(ctx, contract.SettingIncomingLetterDepartmentRecipients)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return []uuid.UUID{}, nil
		}
		return nil, err
	}

	jsonBytes, err := json.Marshal(setting.Value)
	if err != nil {
		return []uuid.UUID{}, nil
	}

	// Try to unmarshal as the structured format first
	var recipientSetting entities.DepartmentRecipientsSetting
	if err := json.Unmarshal(jsonBytes, &recipientSetting); err == nil {
		return recipientSetting.DepartmentIDs, nil
	}

	// If that fails, try to unmarshal as a direct array of UUIDs
	var departmentIDs []uuid.UUID
	if err := json.Unmarshal(jsonBytes, &departmentIDs); err == nil {
		return departmentIDs, nil
	}

	// If both fail, return empty array
	return []uuid.UUID{}, nil
}
