package schedule_storage

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"pinned_message/internal/models"
	"time"
)

type ScheduleStorage struct {
	filepath string
}

func NewScheduleStorage(
	filepath string,
) *ScheduleStorage {
	return &ScheduleStorage{
		filepath: filepath,
	}
}

func (s *ScheduleStorage) SaveSchedule(days []*models.Day) error {
	data, err := json.Marshal(days)
	if err != nil {
		return err
	}
	if err := os.WriteFile(s.filepath, data, 0x777); err != nil {
		return err
	}
	log.Printf("save story to: %s", s.filepath)
	return nil
}

func (s *ScheduleStorage) GetSchedule() ([]*models.Day, error) {
	data, err := os.ReadFile(s.filepath)
	if err != nil {
		return nil, fmt.Errorf("story file %s not found", s.filepath)
	}
	log.Printf("load story from: %s", s.filepath)
	days := []*models.Day{}
	if err := json.Unmarshal(data, &days); err != nil {
		return nil, err
	}
	filterDays := make([]*models.Day, 0, len(days))
	for _, day := range days {
		if isBeforeToday(day.Date) {
			continue
		}
		filterDays = append(filterDays, day)
	}
	return filterDays, nil
}

func isBeforeToday(targetDate time.Time) bool {
	now := time.Now()
	todayMidnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	targetMidnight := time.Date(targetDate.Year(), targetDate.Month(), targetDate.Day(), 0, 0, 0, 0, targetDate.Location())
	return targetMidnight.Before(todayMidnight)
}
