package repository

import (
	"strings"
	"web-qudo-be/app/database"
	"web-qudo-be/app/database/entity"
	"web-qudo-be/utils/paginator"

	"github.com/google/uuid"
	"github.com/rs/zerolog"
)

type CmsContentSubmissionsRepository interface {
	Create(row *entity.CmsContentSubmission) error
	FindByID(clientID uuid.UUID, id uuid.UUID) (*entity.CmsContentSubmission, error)
	List(clientID uuid.UUID, status string, submittedByID *uint, p *paginator.Pagination) ([]entity.CmsContentSubmission, *paginator.Pagination, error)
	Update(row *entity.CmsContentSubmission) error
}

type cmsContentSubmissionsRepository struct {
	DB  *database.Database
	Log zerolog.Logger
}

func NewCmsContentSubmissionsRepository(db *database.Database, log zerolog.Logger) CmsContentSubmissionsRepository {
	return &cmsContentSubmissionsRepository{DB: db, Log: log}
}

func (_i *cmsContentSubmissionsRepository) Create(row *entity.CmsContentSubmission) error {
	return _i.DB.DB.Create(row).Error
}

func (_i *cmsContentSubmissionsRepository) FindByID(clientID uuid.UUID, id uuid.UUID) (*entity.CmsContentSubmission, error) {
	var row entity.CmsContentSubmission
	err := _i.DB.DB.Where("client_id = ? AND id = ?", clientID, id).First(&row).Error
	if err != nil {
		return nil, err
	}
	return &row, nil
}

func (_i *cmsContentSubmissionsRepository) List(clientID uuid.UUID, status string, submittedByID *uint, p *paginator.Pagination) ([]entity.CmsContentSubmission, *paginator.Pagination, error) {
	var rows []entity.CmsContentSubmission
	var count int64

	q := _i.DB.DB.Model(&entity.CmsContentSubmission{}).Where("client_id = ?", clientID)
	st := strings.TrimSpace(strings.ToLower(status))
	if st != "" && st != "all" {
		q = q.Where("status = ?", strings.TrimSpace(status))
	}
	if submittedByID != nil {
		q = q.Where("submitted_by_id = ?", *submittedByID)
	}
	if err := q.Count(&count).Error; err != nil {
		return nil, p, err
	}
	p.Count = count
	p = paginator.Paging(p)
	order := "created_at DESC"
	if p.SortBy != "" {
		dir := "DESC"
		if p.Sort == "asc" {
			dir = "ASC"
		}
		order = p.SortBy + " " + dir
	}
	err := q.Order(order).Offset(p.Offset).Limit(p.Limit).Find(&rows).Error
	return rows, p, err
}

func (_i *cmsContentSubmissionsRepository) Update(row *entity.CmsContentSubmission) error {
	return _i.DB.DB.Save(row).Error
}
