'use server';

const GOTIFY_URL = process.env.GOTIFY_URL;
const GOTIFY_APP_TOKEN = process.env.GOTIFY_APP_TOKEN;

export async function sendGotifyNotification(attempts: number, status: 'won' | 'lost', puzzleId: number, genre?: string | null, score?: number) {
    try {
        const genreText = genre ? `[${genre}] ` : '';
        const title = `Hördle ${genreText}#${puzzleId} ${status === 'won' ? 'Solved!' : 'Failed'}`;
        const scoreText = score !== undefined ? ` with a score of ${score}` : '';
        const message = status === 'won'
            ? `Puzzle #${puzzleId} ${genre ? `(${genre}) ` : ''}was solved in ${attempts} attempt(s)${scoreText}.`
            : `Puzzle #${puzzleId} ${genre ? `(${genre}) ` : ''}was failed after ${attempts} attempt(s)${scoreText}.`;

        const response = await fetch(`${GOTIFY_URL}/message?token=${GOTIFY_APP_TOKEN}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                title: title,
                message: message,
                priority: 5,
            }),
        });

        if (!response.ok) {
            console.error('Failed to send Gotify notification:', await response.text());
        }
    } catch (error) {
        console.error('Error sending Gotify notification:', error);
    }
}

import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

export async function submitRating(songId: number, rating: number, genre?: string | null, isSpecial?: boolean, puzzleNumber?: number) {
    try {
        const song = await prisma.song.findUnique({ where: { id: songId } });
        if (!song) throw new Error('Song not found');

        const newRatingCount = song.ratingCount + 1;
        const newAverageRating = ((song.averageRating * song.ratingCount) + rating) / newRatingCount;

        await prisma.song.update({
            where: { id: songId },
            data: {
                averageRating: newAverageRating,
                ratingCount: newRatingCount,
            },
        });

        // Send Gotify notification for the rating
        let context = 'Global Daily Puzzle';
        if (genre) {
            context = isSpecial ? `Special Puzzle "${genre}"` : `Genre Puzzle "${genre}"`;
        }
        if (puzzleNumber) {
            context += ` #${puzzleNumber}`;
        }

        const title = `Hördle Rating: ${rating} Stars`;
        // Do not show song title/artist to avoid spoilers
        const message = `${context} received a ${rating}-star rating.\nNew Average: ${newAverageRating.toFixed(2)} (${newRatingCount} ratings)`;

        await fetch(`${GOTIFY_URL}/message?token=${GOTIFY_APP_TOKEN}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                title: title,
                message: message,
                priority: 5,
            }),
        });

        return { success: true, averageRating: newAverageRating };
    } catch (error) {
        console.error('Error submitting rating:', error);
        return { success: false, error: 'Failed to submit rating' };
    }
}

export async function sendCommentNotification(puzzleId: number, message: string, originalMessage?: string, genre?: string | null) {
    try {
        const title = `New Curator Comment (Puzzle #${puzzleId})`;
        let body = message;

        if (originalMessage && originalMessage !== message) {
            body = `Original: ${originalMessage}\n\nRewritten: ${message}`;
        }

        if (genre) {
            body = `[${genre}] ${body}`;
        }

        await fetch(`${GOTIFY_URL}/message?token=${GOTIFY_APP_TOKEN}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                title: title,
                message: body,
                priority: 5,
            }),
        });
    } catch (error) {
        console.error('Error sending comment notification:', error);
    }
}
