// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

// Package dateutil provides natural language date parsing for lune commands.
package dateutil

import (
	"fmt"
	"time"

	"git.secluded.site/go-lunatask"
	"github.com/KarpelesLab/strtotime"
)

// Parse parses a natural language date string into a lunatask.Date.
// Uses PHP strtotime syntax.
//
// Supported formats include:
//   - Relative words: "today", "tomorrow", "yesterday"
//   - Relative weekdays: "next Monday", "last Friday"
//   - Relative periods: "next week", "last month", "next year"
//   - Relative offsets: "+3 days", "-1 week", "3 days" (positive assumed)
//   - Compound expressions: "next Friday +2 weeks"
//   - Named dates: "March 5", "January 15 2024"
//   - ISO format: "2024-01-15"
//
// Returns today's date if the input is empty.
func Parse(input string) (lunatask.Date, error) {
	if input == "" {
		return lunatask.Today(), nil
	}

	t, err := strtotime.StrToTime(input)
	if err != nil {
		return lunatask.Date{}, fmt.Errorf("parsing date %q: %w", input, err)
	}

	return lunatask.NewDate(t), nil
}

// ParseInTZ parses a natural language date string with timezone awareness.
// The timezone affects interpretation of relative dates.
func ParseInTZ(input string, tz *time.Location) (lunatask.Date, error) {
	if input == "" {
		return lunatask.Today(), nil
	}

	t, err := strtotime.StrToTime(input, strtotime.InTZ(tz))
	if err != nil {
		return lunatask.Date{}, fmt.Errorf("parsing date %q: %w", input, err)
	}

	return lunatask.NewDate(t), nil
}
