package repository

import (
	"narasi-ahli-be/app/database"
	"narasi-ahli-be/app/database/entity"
	"narasi-ahli-be/app/module/work_history/request"
	"narasi-ahli-be/utils/paginator"
)

type workHistoryRepository struct {
	DB *database.Database
}

type WorkHistoryRepository interface {
	GetAll(userId uint, req request.WorkHistoryQueryRequest) (workHistories []*entity.WorkHistory, paging paginator.Pagination, err error)
	FindOneByUserAndId(userId uint, id uint) (workHistory *entity.WorkHistory, err error)
	Create(workHistory *entity.WorkHistory) (result *entity.WorkHistory, err error)
	Update(userId uint, id uint, workHistory *entity.WorkHistory) (err error)
	Delete(userId uint, id uint) (err error)
}

func NewWorkHistoryRepository(db *database.Database) WorkHistoryRepository {
	return &workHistoryRepository{
		DB: db,
	}
}

func (_i *workHistoryRepository) GetAll(userId uint, req request.WorkHistoryQueryRequest) (workHistories []*entity.WorkHistory, paging paginator.Pagination, err error) {
query := _i.DB.DB.
    Model(&entity.WorkHistory{}).
    Where("user_id = ?", userId)
	
	// Apply filters
	if req.JobTitle != nil {
		query = query.Where("job_title ILIKE ?", "%"+*req.JobTitle+"%")
	}
	if req.CompanyName != nil {
		query = query.Where("company_name ILIKE ?", "%"+*req.CompanyName+"%")
	}
	if req.IsCurrent != nil {
		if *req.IsCurrent {
			query = query.Where("end_date IS NULL")
		} else {
			query = query.Where("end_date IS NOT NULL")
		}
	}

	// Include user relationship
	query = query.Preload("User")

	// Order by start date desc (most recent first)
	query = query.Order("start_date DESC")

	// Apply pagination
	var count int64
	query.Count(&count)
	req.Pagination.Count = count
	req.Pagination = paginator.Paging(req.Pagination)

	err = query.Offset(req.Pagination.Offset).Limit(req.Pagination.Limit).Find(&workHistories).Error
	paging = *req.Pagination

	return
}

func (_i *workHistoryRepository) FindOneByUserAndId(userId uint, id uint) (workHistory *entity.WorkHistory, err error) {
	err = _i.DB.DB.Where("user_id = ? AND id = ?", userId, id).Preload("User").First(&workHistory).Error
	return
}

func (_i *workHistoryRepository) Create(workHistory *entity.WorkHistory) (result *entity.WorkHistory, err error) {
	err = _i.DB.DB.Create(workHistory).Error
	if err != nil {
		return nil, err
	}

	// Reload with relationships
	err = _i.DB.DB.Preload("User").First(&result, workHistory.ID).Error
	return
}

func (_i *workHistoryRepository) Update(userId uint, id uint, workHistory *entity.WorkHistory) (err error) {
	err = _i.DB.DB.Where("user_id = ? AND id = ?", userId, id).Updates(workHistory).Error
	return
}

func (_i *workHistoryRepository) Delete(userId uint, id uint) (err error) {
	err = _i.DB.DB.Where("user_id = ? AND id = ?", userId, id).Delete(&entity.WorkHistory{}).Error
	return
}
