package repository

import (
	dbgen "Yimaru-Backend/gen/db"
	"Yimaru-Backend/internal/domain"
	"Yimaru-Backend/internal/ports"
	"context"

	"github.com/jackc/pgx/v5/pgtype"
)

func NewCourseStore(s *Store) ports.CourseStore { return s }

func (s *Store) CreateCourseCategory(
	ctx context.Context,
	name string,
) (domain.CourseCategory, error) {

	row, err := s.queries.CreateCourseCategory(ctx, dbgen.CreateCourseCategoryParams{
		Name:    name,
		Column2: true,
	})
	if err != nil {
		return domain.CourseCategory{}, err
	}

	return domain.CourseCategory{
		ID:        row.ID,
		Name:      row.Name,
		IsActive:  row.IsActive,
		CreatedAt: row.CreatedAt.Time,
	}, nil
}

func (s *Store) GetCourseCategoryByID(
	ctx context.Context,
	id int64,
) (domain.CourseCategory, error) {

	row, err := s.queries.GetCourseCategoryByID(ctx, id)
	if err != nil {
		return domain.CourseCategory{}, err
	}

	return domain.CourseCategory{
		ID:        row.ID,
		Name:      row.Name,
		IsActive:  row.IsActive,
		CreatedAt: row.CreatedAt.Time,
	}, nil
}

func (s *Store) GetAllCourseCategories(
	ctx context.Context,
	limit int32,
	offset int32,
) ([]domain.CourseCategory, int64, error) {

	rows, err := s.queries.GetAllCourseCategories(ctx, dbgen.GetAllCourseCategoriesParams{
		Limit:  pgtype.Int4{Int32: limit},
		Offset: pgtype.Int4{Int32: offset},
	})
	if err != nil {
		return nil, 0, err
	}

	var (
		categories []domain.CourseCategory
		totalCount int64
	)

	for i, row := range rows {
		if i == 0 {
			totalCount = row.TotalCount
		}

		categories = append(categories, domain.CourseCategory{
			ID:        row.ID,
			Name:      row.Name,
			IsActive:  row.IsActive,
			CreatedAt: row.CreatedAt.Time,
		})
	}

	return categories, totalCount, nil
}

func (s *Store) UpdateCourseCategory(
	ctx context.Context,
	id int64,
	name *string,
	isActive *bool,
) error {

	var (
		nameVal     string
		isActiveVal bool
	)

	if name != nil {
		nameVal = *name
	}

	if isActive != nil {
		isActiveVal = *isActive
	}

	return s.queries.UpdateCourseCategory(ctx, dbgen.UpdateCourseCategoryParams{
		Name:     nameVal,
		IsActive: isActiveVal,
		ID:       id,
	})
}

func (s *Store) DeleteCourseCategory(
	ctx context.Context,
	id int64,
) error {

	return s.queries.DeleteCourseCategory(ctx, id)
}
