package store

type Schedule struct {
	ID        string `json:"id"`
	RoomID    string `json:"room_id"`
	Cron      string `json:"cron"`
	Message   string `json:"message"`
	UserName  string `json:"user_name"`
	Enabled   bool   `json:"enabled"`
	Once      bool   `json:"once"`
	CreatedAt string `json:"created_at"`
	LastRunAt string `json:"last_run_at"`
}

func (s *Store) ListSchedules(roomID string) ([]Schedule, error) {
	rows, err := s.db.Query(
		`SELECT id, room_id, cron, message, user_name, enabled, once, created_at, COALESCE(last_run_at,'')
		 FROM schedules WHERE room_id = ? ORDER BY created_at`, roomID,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var list []Schedule
	for rows.Next() {
		var sch Schedule
		var enabled, once int
		if err := rows.Scan(&sch.ID, &sch.RoomID, &sch.Cron, &sch.Message, &sch.UserName, &enabled, &once, &sch.CreatedAt, &sch.LastRunAt); err != nil {
			return nil, err
		}
		sch.Enabled = enabled != 0
		sch.Once = once != 0
		list = append(list, sch)
	}
	return list, nil
}

func (s *Store) InsertSchedule(sch *Schedule) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	_, err := s.db.Exec(
		`INSERT INTO schedules (id, room_id, cron, message, user_name, enabled, once, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
		sch.ID, sch.RoomID, sch.Cron, sch.Message, sch.UserName, boolToInt(sch.Enabled), boolToInt(sch.Once), sch.CreatedAt,
	)
	return err
}

func (s *Store) UpdateSchedule(sch *Schedule) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	_, err := s.db.Exec(
		`UPDATE schedules SET cron=?, message=?, user_name=?, enabled=?, once=? WHERE id=? AND room_id=?`,
		sch.Cron, sch.Message, sch.UserName, boolToInt(sch.Enabled), boolToInt(sch.Once), sch.ID, sch.RoomID,
	)
	return err
}

func (s *Store) DeleteSchedule(roomID, id string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	_, err := s.db.Exec(`DELETE FROM schedules WHERE id=? AND room_id=?`, id, roomID)
	return err
}

func (s *Store) UpdateLastRun(id, lastRunAt string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	_, err := s.db.Exec(`UPDATE schedules SET last_run_at=? WHERE id=?`, lastRunAt, id)
	return err
}

func (s *Store) DisableSchedule(id string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	_, err := s.db.Exec(`UPDATE schedules SET enabled=0 WHERE id=?`, id)
	return err
}

func (s *Store) GetAllEnabled() ([]Schedule, error) {
	rows, err := s.db.Query(
		`SELECT id, room_id, cron, message, user_name, enabled, once, created_at, COALESCE(last_run_at,'')
		 FROM schedules WHERE enabled=1`,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var list []Schedule
	for rows.Next() {
		var sch Schedule
		var enabled, once int
		if err := rows.Scan(&sch.ID, &sch.RoomID, &sch.Cron, &sch.Message, &sch.UserName, &enabled, &once, &sch.CreatedAt, &sch.LastRunAt); err != nil {
			return nil, err
		}
		sch.Enabled = enabled != 0
		sch.Once = once != 0
		list = append(list, sch)
	}
	return list, nil
}

func boolToInt(b bool) int {
	if b {
		return 1
	}
	return 0
}
