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

import { missingEmbeddingKeysMessage } from '@/lib/connected-agents/connected-agent-ai-settings-server';
import { getOrgPlanQueuePriority } from '@/lib/document-processing/org-queue-priority';
import {
  DOCUMENTS_STORAGE_BUCKET,
  getOrgStorageLimitBytes,
  getOrgUsedDocumentBytes,
  getProjectContextForCurrentUser,
  parseDbBigintToNumber,
} from '@/lib/storage/storage-server-helpers';
import {
  MAX_EDITABLE_BYTES,
  formatEditableSizeLimit,
  getStorageDocumentEditState,
} from '@/lib/storage/storage-editable';
import { hasActiveEmbeddingJobForDocument } from '@/lib/storage/storage-editor-server-helpers';
import { splitFileNameAndExt } from '@/lib/storage/storage-format';
import type { SaveStorageDocumentContentApiResult } from '@/lib/storage/storage-types';
import { getSupabaseServerClient } from '@/lib/supabase/server';

export async function saveProjectStorageDocumentContentForCurrentUser(
  projectId: string,
  documentId: string,
  payload: { content: string },
): Promise<SaveStorageDocumentContentApiResult> {
  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' };

  if (typeof payload?.content !== 'string') {
    return { ok: false, message: 'File content is required.', code: 'BAD_REQUEST' };
  }

  const supabase = await getSupabaseServerClient();
  const { data: authData, error: authError } = await supabase.auth.getUser();
  if (authError) return { ok: false, message: authError.message, code: 'BAD_REQUEST' };
  if (!authData.user) return { ok: false, message: 'Unauthorized', code: 'FORBIDDEN' };

  const { data: doc, error: docErr } = await supabase
    .from('documents')
    .select(
      'id,project_agent_id,organization_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 projectAgentId = String(doc.project_agent_id);
  const projectAgentRow = context.projectAgentRows.find((r) => r.projectAgentId === projectAgentId);
  if (!projectAgentRow) {
    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' };

  const { extLowerNoDot } = splitFileNameAndExt(String(doc.file_name ?? ''));
  const previousBytes = parseDbBigintToNumber(doc.file_size_bytes);
  const editState = getStorageDocumentEditState({
    fileExtension: extLowerNoDot,
    fileSizeBytes: previousBytes,
    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 encoded = new TextEncoder().encode(payload.content);
  const nextBytes = encoded.byteLength;
  if (nextBytes > MAX_EDITABLE_BYTES) {
    return {
      ok: false,
      message: `The edited file is larger than ${formatEditableSizeLimit()}. Remove some content, or upload a new file instead.`,
      code: 'BAD_REQUEST',
    };
  }

  // An edit can grow the file, so it has to respect the org quota the same way
  // an upload does.
  if (nextBytes > previousBytes) {
    const limit = await getOrgStorageLimitBytes(context.organizationId);
    if (!limit.ok) return { ok: false, message: limit.message, code: 'BAD_REQUEST' };

    if (limit.allowedBytes !== null) {
      const used = await getOrgUsedDocumentBytes(context.organizationId);
      if (!used.ok) return { ok: false, message: used.message, code: 'BAD_REQUEST' };

      const projected = used.usedBytes - previousBytes + nextBytes;
      if (projected > limit.allowedBytes) {
        return {
          ok: false,
          message: 'Saving this file would exceed your organization storage limit.',
          code: 'QUOTA_EXCEEDED',
        };
      }
    }
  }

  // Saving re-embeds the document on the agent's own key; refuse before overwriting it.
  if (projectAgentRow.requiresDocumentEmbedding) {
    const keys = await missingEmbeddingKeysMessage(supabase, [projectAgentId]);
    if (!keys.ok) return { ok: false, message: keys.message, code: 'BAD_REQUEST' };
    if (keys.message) return { ok: false, message: keys.message, code: 'BAD_REQUEST' };
  }

  const contentType = String(doc.file_type ?? '').trim() || 'text/plain';
  const storagePath = String(doc.storage_path);

  const uploadRes = await supabase.storage
    .from(DOCUMENTS_STORAGE_BUCKET)
    .upload(storagePath, new Blob([encoded], { type: contentType }), {
      upsert: true,
      contentType,
    });
  if (uploadRes.error) {
    return { ok: false, message: uploadRes.error.message, code: 'BAD_REQUEST' };
  }

  const needsEmbedding = Boolean(projectAgentRow.requiresDocumentEmbedding);
  const nowIso = new Date().toISOString();

  const { error: updateErr } = await supabase
    .from('documents')
    .update({
      file_size_bytes: nextBytes,
      content_modified_at: nowIso,
      status: needsEmbedding ? 'pending' : 'ready',
      chunk_count: 0,
      processed_at: needsEmbedding ? null : nowIso,
    })
    .eq('id', docId);
  if (updateErr) return { ok: false, message: updateErr.message, code: 'BAD_REQUEST' };

  // The stored chunks describe the previous text. Leaving them in place is the
  // dangerous failure: the agent would keep answering from content that no
  // longer exists in the file, with nothing in the UI to suggest it.
  const { error: deleteChunksErr } = await supabase
    .from('document_chunks')
    .delete()
    .eq('document_id', docId);
  if (deleteChunksErr) {
    return { ok: false, message: deleteChunksErr.message, code: 'BAD_REQUEST' };
  }

  if (!needsEmbedding) {
    return { ok: true, documentId: docId, fileSizeBytes: nextBytes, reprocessing: false };
  }

  const queuePriority = await getOrgPlanQueuePriority(supabase, context.organizationId);
  const { error: jobErr } = await supabase.from('document_processing_jobs').insert({
    organization_id: context.organizationId,
    project_id: context.projectId,
    document_id: docId,
    status: 'queued',
    job_type: 'embed_document',
    priority: queuePriority,
    max_attempts: 2,
    payload: {
      document_id: docId,
      file_path: storagePath,
      storage_bucket: DOCUMENTS_STORAGE_BUCKET,
      project_agent_id: projectAgentId,
      agent_id: projectAgentRow.agentId,
      requested_by_user_id: authData.user.id,
      file_name: String(doc.file_name ?? ''),
      file_type: contentType,
    },
  });
  if (jobErr) return { ok: false, message: jobErr.message, code: 'BAD_REQUEST' };

  return { ok: true, documentId: docId, fileSizeBytes: nextBytes, reprocessing: true };
}
