---
import '../styles/global.css';
import App from '@/components/layout/MainLayout';
import { db, mirrorJobs } from '@/lib/db';
import ThemeScript from '@/components/theme/ThemeScript.astro';

// Fetch activity data from the database
let activityData = [];

try {
  // Fetch activity from mirror jobs
  const jobs = await db.select().from(mirrorJobs).limit(20);
  activityData = jobs.flatMap((job: any) => {
    // Check if log exists before parsing
    if (!job.log) {
      console.warn(`Job ${job.id} has no log data`);
      return [];
    }
    
    try {
      const log = JSON.parse(job.log);
      if (!Array.isArray(log)) {
        console.warn(`Job ${job.id} log is not an array`);
        return [];
      }
      
      return log.map((entry: any) => ({
        id: `${job.id}-${entry.timestamp}`,
        message: entry.message,
        timestamp: new Date(entry.timestamp),
        status: entry.level,
        details: entry.details,
        repositoryName: entry.repositoryName,
      }));
    } catch (parseError) {
      console.error(`Failed to parse log for job ${job.id}:`, parseError);
      return [];
    }
  }).slice(0, 20);
} catch (error) {
  console.error('Error fetching activity:', error);
  // Fallback to empty array if database access fails
  activityData = [];
}

// Client-side function to handle refresh
const handleRefresh = () => {
  console.log('Refreshing activity log');
  // In a real implementation, this would call the API to refresh the activity log
};
---

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <meta name="generator" content={Astro.generator} />
    <title>Activity Log - Gitea Mirror</title>
    <ThemeScript />
  </head>
  <body>
    <App page='activity-log'client:load />
  </body>
</html>
