/*
*  author: Yagnik Poshiya
*  organization: Webbrains Technologies Private Limited
*/

import {
  DOCUMENTS_STORAGE_BUCKET,
  getProjectContextForCurrentUser,
} from '@/lib/storage/storage-server-helpers';
import { getStorageDocumentEditState } from '@/lib/storage/storage-editable';
import { splitFileNameAndExt } from '@/lib/storage/storage-format';
import { hasActiveEmbeddingJobForDocument } from '@/lib/storage/storage-editor-server-helpers';
import type { ReadStorageDocumentContentApiResult } from '@/lib/storage/storage-types';
import { getSupabaseServerClient } from '@/lib/supabase/server';

export async function readProjectStorageDocumentContentForCurrentUser(
  projectId: string,
  documentId: string,
): Promise<ReadStorageDocumentContentApiResult> {
  const context = await getProjectContextForCurrentUser(projectId);
  if (!context.ok) return { ok: false, message: context.message, code: context.code };

  const docId = String(documentId ?? '').trim();
  if (!docId) return { ok: false, message: 'Missing document id.', code: 'BAD_REQUEST' };

  const supabase = await getSupabaseServerClient();

  const { data: doc, error: docErr } = await supabase
    .from('documents')
    .select(
      'id,project_agent_id,file_name,file_type,file_size_bytes,status,storage_bucket,storage_path,is_deleted',
    )
    .eq('id', docId)
    .maybeSingle();

  if (docErr) return { ok: false, message: docErr.message, code: 'BAD_REQUEST' };
  if (!doc || doc.is_deleted) {
    return { ok: false, message: 'Document not found.', code: 'NOT_FOUND' };
  }

  const projectAgentIdSet = new Set(context.projectAgentRows.map((r) => r.projectAgentId));
  if (!projectAgentIdSet.has(doc.project_agent_id as string)) {
    return { ok: false, message: 'You do not have access to this document.', code: 'FORBIDDEN' };
  }
  if (doc.storage_bucket !== DOCUMENTS_STORAGE_BUCKET) {
    return { ok: false, message: 'Only active storage documents can be edited.', code: 'BAD_REQUEST' };
  }

  const activeJob = await hasActiveEmbeddingJobForDocument(supabase, docId);
  if (!activeJob.ok) return { ok: false, message: activeJob.message, code: 'BAD_REQUEST' };

  // Re-checked here rather than trusted from the client: the row may have
  // changed since the table was rendered.
  const { extLowerNoDot } = splitFileNameAndExt(String(doc.file_name ?? ''));
  const editState = getStorageDocumentEditState({
    fileExtension: extLowerNoDot,
    fileSizeBytes: Number(doc.file_size_bytes ?? 0),
    status: String(doc.status ?? ''),
    hasActiveEmbeddingJob: activeJob.active,
  });
  if (!editState.editable) {
    return { ok: false, message: editState.reason ?? 'This file cannot be edited.', code: 'BAD_REQUEST' };
  }

  const { data: fileBlob, error: dlErr } = await supabase.storage
    .from(DOCUMENTS_STORAGE_BUCKET)
    .download(String(doc.storage_path));

  if (dlErr) return { ok: false, message: dlErr.message, code: 'BAD_REQUEST' };
  if (!fileBlob) return { ok: false, message: 'Empty file.', code: 'BAD_REQUEST' };

  // Strict decode. A lossy decode would put replacement characters in the
  // editor, and saving that back would silently destroy the original bytes.
  let content: string;
  try {
    const buffer = await fileBlob.arrayBuffer();
    content = new TextDecoder('utf-8', { fatal: true }).decode(buffer);
  } catch {
    return {
      ok: false,
      message: 'This file is not valid UTF-8 text, so it cannot be edited here safely.',
      code: 'BAD_REQUEST',
    };
  }

  return {
    ok: true,
    documentId: String(doc.id),
    fileName: String(doc.file_name ?? ''),
    fileExtension: extLowerNoDot,
    content,
  };
}
