using AsadiTools.Data;
using AsadiTools.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;

namespace AsadiTools.Pages.Admin.Blog;

[Authorize(AuthenticationSchemes = "AdminCookie")]
public class AdminBlogCreateModel(AppDbContext db) : PageModel
{
    [BindProperty] public BlogPostInput Input { get; set; } = new();

    public void OnGet() { ViewData["Title"] = "نوشته جدید"; }

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid) return Page();

        var slug = string.IsNullOrWhiteSpace(Input.Slug)
            ? Input.Title.ToLower()
                  .Replace(" ", "-")
                  .Replace("،", "")
                  .Replace(".", "-")
            : Input.Slug.Trim();

        var now = DateTime.Now;
        db.BlogPosts.Add(new BlogPost
        {
            Title           = Input.Title,
            Slug            = slug,
            Content         = Input.Content,
            Excerpt         = Input.Excerpt,
            MetaDescription = Input.MetaDescription,
            FeaturedImage   = string.IsNullOrWhiteSpace(Input.FeaturedImage) ? null : Input.FeaturedImage,
            Tags            = Input.Tags,
            IsPublished     = Input.IsPublished,
            PublishedAt     = Input.IsPublished ? now : null,
            CreatedAt       = now,
            UpdatedAt       = now,
        });
        await db.SaveChangesAsync();
        return RedirectToPage("/Admin/Blog/Index");
    }
}

public class BlogPostInput
{
    [Required] public string Title { get; set; } = string.Empty;
    public string? Slug { get; set; }
    [Required] public string Content { get; set; } = string.Empty;
    public string? Excerpt { get; set; }
    public string? MetaDescription { get; set; }
    public string? FeaturedImage { get; set; }
    public string? Tags { get; set; }
    public bool IsPublished { get; set; }
}
