package system

import (
	"context"
	"encoding/json"
	"kra/internal/biz/system"
	"time"

	"kra/pkg/database/gormkit"
	"kra/pkg/database/pagination"

	"gorm.io/gorm"
)

type announcementPO struct {
	ID          uint `gorm:"primaryKey"`
	CreatedAt   time.Time
	UpdatedAt   time.Time
	DeletedAt   gorm.DeletedAt `gorm:"index"`
	Title       string
	Content     string `gorm:"type:text"`
	UserID      *int   `gorm:"column:user_id"`
	Attachments gormkit.JSON
}

func (announcementPO) TableName() string { return "sys_announcements" }

type announcementRepo struct{ data Provider }

func NewAnnouncementRepo(data Provider) system.AnnouncementRepo { return &announcementRepo{data: data} }

func newAnnouncement(item *system.Announcement) announcementPO {
	return announcementPO{ID: item.ID, Title: item.Title, Content: item.Content, UserID: item.UserID, Attachments: gormkit.JSON(item.Attachments)}
}

func announcementToBiz(item announcementPO) *system.Announcement {
	return &system.Announcement{ID: item.ID, CreatedAt: item.CreatedAt, UpdatedAt: item.UpdatedAt, Title: item.Title, Content: item.Content, UserID: item.UserID, Attachments: json.RawMessage(item.Attachments)}
}

func (r *announcementRepo) Create(ctx context.Context, item *system.Announcement) error {
	po := newAnnouncement(item)
	if err := r.data.DB().WithContext(ctx).Create(&po).Error; err != nil {
		return err
	}
	item.ID, item.CreatedAt, item.UpdatedAt = po.ID, po.CreatedAt, po.UpdatedAt
	return nil
}

func (r *announcementRepo) Delete(ctx context.Context, id string) error {
	return r.data.DB().WithContext(ctx).Delete(&announcementPO{}, "id = ?", id).Error
}

func (r *announcementRepo) DeleteByIDs(ctx context.Context, ids []string) error {
	return r.data.DB().WithContext(ctx).Delete(&[]announcementPO{}, "id IN ?", ids).Error
}

func (r *announcementRepo) Update(ctx context.Context, item *system.Announcement) error {
	po := newAnnouncement(item)
	return r.data.DB().WithContext(ctx).Model(&announcementPO{}).Where("id = ?", item.ID).Updates(&po).Error
}

func (r *announcementRepo) Find(ctx context.Context, id string) (*system.Announcement, error) {
	var po announcementPO
	if err := r.data.DB().WithContext(ctx).Where("id = ?", id).First(&po).Error; err != nil {
		return nil, err
	}
	return announcementToBiz(po), nil
}

func (r *announcementRepo) List(ctx context.Context, filter system.AnnouncementFilter) ([]*system.Announcement, int64, error) {
	db := r.data.DB().WithContext(ctx).Model(&announcementPO{})
	if filter.StartCreatedAt != nil && filter.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", filter.StartCreatedAt, filter.EndCreatedAt)
	}
	var total int64
	if err := db.Count(&total).Error; err != nil {
		return nil, 0, err
	}
	if filter.PageSize > 0 {
		db = pagination.Apply(db, filter.Page, filter.PageSize, 100)
	}
	var pos []announcementPO
	if err := db.Find(&pos).Error; err != nil {
		return nil, 0, err
	}
	items := make([]*system.Announcement, 0, len(pos))
	for _, po := range pos {
		items = append(items, announcementToBiz(po))
	}
	return items, total, nil
}

func (r *announcementRepo) UserOptions(ctx context.Context) ([]system.UserOption, error) {
	var rows []struct {
		Label string
		Value uint
	}
	// The generated data-source endpoint is best effort: return collected
	// options even when the underlying scan reports an error.
	_ = r.data.DB().WithContext(ctx).Table("sys_users").Select("nick_name AS label, id AS value").Scan(&rows).Error
	items := make([]system.UserOption, 0, len(rows))
	for _, row := range rows {
		items = append(items, system.UserOption{Label: row.Label, Value: row.Value})
	}
	return items, nil
}
