from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Post
from .forms import PostForm

# 게시글 목록
def post_list(request):
    posts = Post.objects.all().order_by('-created_at')
    return render(request, 'blog/post_list.html', {'posts': posts})

# 게시글 상세 보기
def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, 'blog/post_detail.html', {'post': post})

@login_required
def create_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user  # 작성자 정보 추가
            post.save()
            form.save_m2m()
            return redirect('blog:post_list')
    else:
        form = PostForm()
    return render(request, 'blog/create_post.html', {'form': form})



@login_required
def update_post(request, pk):
    post = get_object_or_404(Post, pk=pk)

    # 작성자만 수정 가능하도록 권한 검사
    if post.author != request.user:
        return redirect('blog:post_list')

    if request.method == 'POST':
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            form.save()
            return redirect('blog:post_detail', pk=post.pk)
    else:
        form = PostForm(instance=post)

    return render(request, 'blog/update_post.html', {'form': form, 'post': post})

@login_required
def delete_post(request, pk):
    post = get_object_or_404(Post, pk=pk)

    # 작성자만 삭제 가능
    if post.author != request.user:
        return redirect('blog:post_list')

    # POST 요청일 때 삭제
    if request.method == 'POST':
        post.delete()
        return redirect('blog:post_list')

    return render(request, 'blog/confirm_delete.html', {'post': post})