// app/admin/dashboard/posts/page.tsx
import PostsTable from '@/app/components/admin/posts/PostsTable';
import { authService } from '@/services/auth-service';
import { PERMISSIONS } from '@/lib/permissions';
import { redirect } from 'next/navigation';
import { getTokenFromCookies } from '@/lib/auth-utils';
import { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'Blog Posts',
  description: 'Manage blog posts in the admin panel.',
};

async function getInitialData(token: string) {
  try {
    const res = await fetch(
      `${process.env.NEXTAUTH_URL}/api/backend/admin/posts?page=1&limit=10`,
      { cache: 'no-store', headers: { Authorization: `Bearer ${token}` } }
    );
    if (res.ok) return await res.json();
  } catch (e) {
    console.error('Failed to fetch initial posts:', e);
  }
  return null;
}

export default async function PostsPage() {
  const token = await getTokenFromCookies();
  if (!token) redirect('/admin/login');

  const hasPermission = await authService.checkUserPermission(token, PERMISSIONS.CONTENT_READ);
  if (!hasPermission) {
    return (
      <div className="space-y-6">
        <div className="bg-var-danger-bg border border-var-danger-border rounded-2xl p-6 text-center">
          <h1 className="text-2xl font-bold text-var-danger-text">Access Denied</h1>
          <p className="text-var-danger-text mt-2">You don&apos;t have permission to view posts.</p>
        </div>
      </div>
    );
  }

  const initialData = await getInitialData(token);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-var-text">Blog Posts</h1>
        <p className="text-var-text-secondary mt-1">
          Create and manage your blog content. Assign sidebars to posts for enhanced layouts.
        </p>
      </div>
      <PostsTable initialData={initialData} />
    </div>
  );
}