import { serve } from 'https://deno.land/std@0.177.0/http/server.ts';
import { S3Client, DeleteObjectCommand } from 'https://esm.sh/@aws-sdk/client-s3@3.470.0';
import { createServiceClient } from '../_shared/supabase-client.ts';

const ALLOWED_ORIGIN = Deno.env.get('ALLOWED_ORIGIN') || 'https://sojorn.net';

const corsHeaders = {
  'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

const R2_ENDPOINT = (Deno.env.get('R2_ENDPOINT') ?? '').trim();
const R2_ACCOUNT_ID = (Deno.env.get('R2_ACCOUNT_ID') ?? '').trim();
const R2_ACCESS_KEY_ID = (Deno.env.get('R2_ACCESS_KEY_ID') ?? Deno.env.get('R2_ACCESS_KEY') ?? '').trim();
const R2_SECRET_ACCESS_KEY = (Deno.env.get('R2_SECRET_ACCESS_KEY') ?? Deno.env.get('R2_SECRET_KEY') ?? '').trim();
const R2_BUCKET_NAME = (Deno.env.get('R2_BUCKET_NAME') ?? '').trim();
const DEFAULT_BUCKET_NAME = 'sojorn-media';

const RESOLVED_ENDPOINT = R2_ENDPOINT || (R2_ACCOUNT_ID ? `https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com` : '');
const RESOLVED_BUCKET = R2_BUCKET_NAME || DEFAULT_BUCKET_NAME;

const supabase = createServiceClient();

function extractObjectKey(imageUrl: string, bucketName: string): string | null {
  try {
    const url = new URL(imageUrl);
    let key = url.pathname.replace(/^\/+/, '');
    if (!key) return null;
    if (bucketName && key.startsWith(`${bucketName}/`)) {
      key = key.slice(bucketName.length + 1);
    }
    return decodeURIComponent(key);
  } catch (_) {
    return null;
  }
}

serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: { ...corsHeaders, 'Access-Control-Allow-Methods': 'POST OPTIONS' } });
  }

  if (req.method !== 'POST') {
    return new Response(JSON.stringify({ error: 'Method not allowed' }), {
      status: 405,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }

  if (!RESOLVED_ENDPOINT || !R2_ACCESS_KEY_ID || !R2_SECRET_ACCESS_KEY || !RESOLVED_BUCKET) {
    return new Response(JSON.stringify({ error: 'Missing R2 configuration' }), {
      status: 500,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }

  const r2 = new S3Client({
    region: 'auto',
    endpoint: RESOLVED_ENDPOINT,
    credentials: {
      accessKeyId: R2_ACCESS_KEY_ID,
      secretAccessKey: R2_SECRET_ACCESS_KEY,
    },
    forcePathStyle: true,
  });

  try {
    const maxBatches = 50;
    const batchSize = 100;
    const maxRuntimeMs = 25000;
    const startTime = Date.now();

    let processedCount = 0;
    let deletedCount = 0;
    let skippedCount = 0;
    let batches = 0;

    while (batches < maxBatches && Date.now() - startTime < maxRuntimeMs) {
      const { data: posts, error } = await supabase
        .from('posts')
        .select('id, image_url, expires_at')
        .lt('expires_at', new Date().toISOString())
        .order('expires_at', { ascending: true })
        .limit(batchSize);

      if (error) {
        console.error('Error fetching expired posts:', error);
        return new Response(JSON.stringify({ error: 'Failed to fetch expired posts' }), {
          status: 500,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' },
        });
      }

      const expiredPosts = posts ?? [];
      if (expiredPosts.length === 0) break;

      processedCount += expiredPosts.length;
      batches += 1;

      for (const post of expiredPosts) {
        if (post.image_url) {
          const key = extractObjectKey(post.image_url, RESOLVED_BUCKET);
          if (!key) {
            console.error('Could not parse image key:', { post_id: post.id, image_url: post.image_url });
            skippedCount += 1;
            continue;
          }

          try {
            await r2.send(
              new DeleteObjectCommand({
                Bucket: RESOLVED_BUCKET,
                Key: key,
              })
            );
          } catch (error) {
            console.error('R2 deletion failed:', { post_id: post.id, error });
            skippedCount += 1;
            continue;
          }
        }

        const { error: deleteError } = await supabase
          .from('posts')
          .delete()
          .eq('id', post.id);

        if (deleteError) {
          console.error('Failed to delete post row:', { post_id: post.id, error: deleteError });
          skippedCount += 1;
          continue;
        }

        deletedCount += 1;
      }
    }

    return new Response(
      JSON.stringify({
        processed: processedCount,
        deleted: deletedCount,
        skipped: skippedCount,
        batches,
      }),
      {
        status: 200,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      }
    );
  } catch (error) {
    console.error('Unexpected cleanup error:', error);
    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
});
