import type { APIRoute } from 'astro';

export const GET: APIRoute = async ({ request }) => {
  try {
    const username = 'Richard';
    const url = `https://git.365devnet.eu/api/v1/users/${username}/activities/feeds`;
    
    const headers: HeadersInit = { 
      accept: 'application/json' 
    };
    
    if (import.meta.env.GITEA_TOKEN) {
      headers['Authorization'] = `token ${import.meta.env.GITEA_TOKEN}`;
    }
    
    const response = await fetch(url, { headers, redirect: 'follow', cache: 'no-store' });
    
    if (!response.ok) {
      throw new Error(`Gitea API responded with status: ${response.status}`);
    }
    
    const feeds = await response.json();
    
    // Only keep commit_repo events
    const commits: Array<{
      sha: string;
      message: string;
      author: string;
      date: string;
      repo: string;
      repo_url: string;
      compare_url: string;
    }> = [];
    
    for (const feed of feeds) {
      if (feed.op_type === 'commit_repo' && feed.content) {
        let content;
        try {
          content = JSON.parse(feed.content);
        } catch {
          continue;
        }
        // Each feed may have multiple commits
        if (content.Commits && Array.isArray(content.Commits)) {
          for (const commit of content.Commits) {
            commits.push({
              sha: commit.Sha1,
              message: commit.Message,
              author: commit.AuthorName,
              date: commit.Timestamp,
              repo: feed.repo ? feed.repo.full_name : '',
              repo_url: feed.repo ? feed.repo.html_url : '',
              compare_url: content.CompareURL ? `https://git.365devnet.eu/${content.CompareURL}` : '',
            });
          }
        }
      }
    }

    // Pagination
    const { searchParams } = new URL(request.url);
    const limit = parseInt(searchParams.get('limit') || '5', 10);
    const offset = parseInt(searchParams.get('offset') || '0', 10);
    const pagedCommits = commits.slice(offset, offset + limit);
    const hasMore = offset + limit < commits.length;
    
    return new Response(JSON.stringify({
      success: true,
      commits: pagedCommits,
      hasMore,
      total: commits.length,
      timestamp: new Date().toISOString()
    }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': '0'
      }
    });
    
  } catch (error) {
    console.error('Error fetching commits:', error);
    
    return new Response(JSON.stringify({
      success: false,
      error: 'Failed to fetch commits',
      timestamp: new Date().toISOString()
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
}; 