using Agent86.Models;
using Agent86.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;

namespace Agent86.Pages
{
    [Authorize(Roles = "user")]
    public class IndexModel : PageModel
    {

        private readonly OllamaService _ollama;

        public IndexModel(OllamaService ollama)
        {
            _ollama = ollama;
        }

        [BindProperty]
        public string UserInput { get; set; }

        public List<ChatMessage> ChatHistory { get; set; } = new();

        private const string SessionKey = "ChatHistory";

        private const string RoleplayContext = @"you are a movie theater with two theaters.
You are contacted by a software developer who wants to create an online shop for your movie theater.
You want this online shop to sell tickets for the events and possibly also to sell popcorn and drinks.
Stay in character as a curious and slightly demanding customer.";

        public void OnGet()
        {
            LoadHistory();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            LoadHistory();

            ChatHistory.Add(new ChatMessage { Role = "user", Content = UserInput });

            var reply = await _ollama.GenerateReplyAsync(ChatHistory, RoleplayContext);

            ChatHistory.Add(new ChatMessage { Role = "assistant", Content = reply });

            SaveHistory();

            return RedirectToPage();
        }

        private void LoadHistory()
        {
            var data = HttpContext.Session.GetString(SessionKey);
            if (!string.IsNullOrEmpty(data))
            {
                ChatHistory = JsonConvert.DeserializeObject<List<ChatMessage>>(data);
            }
        }

        private void SaveHistory()
        {
            HttpContext.Session.SetString(SessionKey,
                JsonConvert.SerializeObject(ChatHistory));
        }
    }
}
