package repository

import (
	"apskel-pos-be/internal/entities"
	"context"

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

type OutletSettingRepositoryImpl struct {
	db *gorm.DB
}

func NewOutletSettingRepositoryImpl(db *gorm.DB) *OutletSettingRepositoryImpl {
	return &OutletSettingRepositoryImpl{
		db: db,
	}
}

func (r *OutletSettingRepositoryImpl) Create(ctx context.Context, setting *entities.OutletSetting) error {
	return r.db.WithContext(ctx).Create(setting).Error
}

func (r *OutletSettingRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.OutletSetting, error) {
	var setting entities.OutletSetting
	err := r.db.WithContext(ctx).First(&setting, "id = ?", id).Error
	if err != nil {
		return nil, err
	}
	return &setting, nil
}

func (r *OutletSettingRepositoryImpl) GetByOutletIDAndKey(ctx context.Context, outletID uuid.UUID, key string) (*entities.OutletSetting, error) {
	var setting entities.OutletSetting
	err := r.db.WithContext(ctx).Where("outlet_id = ? AND key = ?", outletID, key).First(&setting).Error
	if err != nil {
		return nil, err
	}
	return &setting, nil
}

func (r *OutletSettingRepositoryImpl) GetByOutletID(ctx context.Context, outletID uuid.UUID) ([]*entities.OutletSetting, error) {
	var settings []*entities.OutletSetting
	err := r.db.WithContext(ctx).Where("outlet_id = ?", outletID).Find(&settings).Error
	return settings, err
}

func (r *OutletSettingRepositoryImpl) Update(ctx context.Context, setting *entities.OutletSetting) error {
	return r.db.WithContext(ctx).Save(setting).Error
}

func (r *OutletSettingRepositoryImpl) Upsert(ctx context.Context, setting *entities.OutletSetting) error {
	return r.db.WithContext(ctx).Save(setting).Error
}

func (r *OutletSettingRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
	return r.db.WithContext(ctx).Delete(&entities.OutletSetting{}, "id = ?", id).Error
}

func (r *OutletSettingRepositoryImpl) DeleteByOutletIDAndKey(ctx context.Context, outletID uuid.UUID, key string) error {
	return r.db.WithContext(ctx).Delete(&entities.OutletSetting{}, "outlet_id = ? AND key = ?", outletID, key).Error
}

func (r *OutletSettingRepositoryImpl) GetPrinterSettingsByOutletID(ctx context.Context, outletID uuid.UUID) (map[string]string, error) {
	var settings []*entities.OutletSetting
	err := r.db.WithContext(ctx).Where("outlet_id = ? AND key IN (?, ?, ?, ?, ?, ?)",
		outletID,
		"printer_outlet_name",
		"printer_address",
		"printer_phone_number",
		"printer_paper_size",
		"printer_footer",
		"printer_footer_hashtag",
	).Find(&settings).Error

	if err != nil {
		return nil, err
	}

	result := make(map[string]string)
	for _, setting := range settings {
		result[setting.Key] = setting.Value
	}

	return result, nil
}
