import { RecoveryTracker } from './RecoveryTracker';

export class WeedTracker extends RecoveryTracker {
    calculateMinutesFree(precise: boolean = false): number {
        // 1. Try to use precise timestamp from preferences first
        if (this.preferences?.lastWeedUsageTime) {
            const now = new Date();
            const lastUsageTime = new Date(this.preferences.lastWeedUsageTime);
            const diffMs = now.getTime() - lastUsageTime.getTime();
            const minutes = this.msToMinutes(diffMs, precise);

            // Validation: Ensure the timestamp aligns with the last recorded usage date.
            const lastRecordedDateStr = this.getLastRecordedDate();

            if (lastRecordedDateStr) {
                const lastRecordedDate = new Date(lastRecordedDateStr);
                lastRecordedDate.setHours(0, 0, 0, 0);

                if (lastUsageTime < lastRecordedDate) {
                    return this.calculateDateBasedMinutes(lastRecordedDateStr, precise);
                }
            }

            return minutes;
        }

        // 2. Fallback to date-based logic if no timestamp exists
        const lastDateStr = this.getLastRecordedDate();
        
        // 3. If no weed usage ever recorded, use tracking start date
        if (!lastDateStr) {
            if (this.preferences?.trackingStartDate) {
                const startDate = new Date(this.preferences.trackingStartDate);
                startDate.setHours(0, 0, 0, 0); // Count from start of tracking day
                const now = new Date();
                const diffMs = now.getTime() - startDate.getTime();
                return this.msToMinutes(diffMs, precise);
            }
            return 0; // No usage and no tracking start date
        }

        return this.calculateDateBasedMinutes(lastDateStr, precise);
    }

    private getLastRecordedDate(): string | null {
        const weedData = this.usageData
            .filter((e) => e.substance === 'weed' && e.count > 0)
            .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

        return weedData.length > 0 ? weedData[0].date : null;
    }

    private calculateDateBasedMinutes(dateStr: string, precise: boolean): number {
        const now = new Date();
        const todayStr = now.toISOString().split('T')[0];

        // If the last usage was today but we have no timestamp, reset to 0
        if (dateStr === todayStr) {
            return 0;
        }

        // For past days, count from the END of that day (23:59:59)
        const lastUsageDate = new Date(dateStr);
        lastUsageDate.setHours(23, 59, 59, 999);

        const diffMs = now.getTime() - lastUsageDate.getTime();
        return this.msToMinutes(diffMs, precise);
    }
}
