/**
 * In-App Feedback repository — Cosmos DB CRUD.
 */

import { getRegisteredContainer } from '@bytelyst/cosmos';
import crypto from 'node:crypto';
import type {
  FeedbackDoc,
  CreateFeedbackInput,
  UpdateFeedbackInput,
  QueryFeedbackInput,
} from './types.js';

function getContainer() {
  return getRegisteredContainer('feedback');
}

export async function createFeedback(
  productId: string,
  userId: string,
  input: CreateFeedbackInput
): Promise<FeedbackDoc> {
  const now = new Date().toISOString();
  const doc: FeedbackDoc = {
    id: `fb_${crypto.randomUUID()}`,
    productId,
    userId,
    type: input.type,
    title: input.title,
    body: input.body ?? '',
    rating: input.rating ?? null,
    screen: input.screen ?? null,
    appVersion: input.appVersion ?? null,
    platform: input.platform ?? null,
    status: 'new',
    adminNotes: null,
    // Screenshot fields (Phase 1.2)
    screenshotBlobPath: input.screenshotBlobPath,
    screenshotContentType: input.screenshotContentType,
    screenshotSizeBytes: input.screenshotSizeBytes,
    // Device context (Phase 1.2)
    deviceContext: input.deviceContext,
    createdAt: now,
    updatedAt: now,
  };
  await getContainer().items.create(doc);
  return doc;
}

export async function getFeedback(id: string, productId: string): Promise<FeedbackDoc | null> {
  try {
    const { resource } = await getContainer().item(id, productId).read<FeedbackDoc>();
    return resource ?? null;
  } catch {
    return null;
  }
}

export async function listFeedback(
  productId: string,
  query: QueryFeedbackInput
): Promise<FeedbackDoc[]> {
  const conditions = ['c.productId = @pid'];
  const params: { name: string; value: string | number }[] = [{ name: '@pid', value: productId }];

  if (query.type) {
    conditions.push('c.type = @type');
    params.push({ name: '@type', value: query.type });
  }
  if (query.status) {
    conditions.push('c.status = @status');
    params.push({ name: '@status', value: query.status });
  }

  const sql = `SELECT * FROM c WHERE ${conditions.join(' AND ')} ORDER BY c.createdAt DESC OFFSET @offset LIMIT @limit`;
  params.push({ name: '@offset', value: query.offset ?? 0 });
  params.push({ name: '@limit', value: query.limit ?? 50 });

  const { resources } = await getContainer()
    .items.query<FeedbackDoc>({ query: sql, parameters: params })
    .fetchAll();
  return resources;
}

export async function updateFeedback(
  id: string,
  productId: string,
  updates: UpdateFeedbackInput
): Promise<FeedbackDoc | null> {
  const existing = await getFeedback(id, productId);
  if (!existing) return null;

  const updated: FeedbackDoc = {
    ...existing,
    ...updates,
    updatedAt: new Date().toISOString(),
  };
  await getContainer().item(id, productId).replace(updated);
  return updated;
}

export async function deleteFeedback(id: string, productId: string): Promise<boolean> {
  try {
    await getContainer().item(id, productId).delete();
    return true;
  } catch {
    return false;
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Screenshot management (Phase 1.2)
// ─────────────────────────────────────────────────────────────────────────────

/**
 * Generate blob path for feedback screenshot.
 * Pattern: feedback/{productId}/{feedbackId}/{screenshotId}.png
 */
export function generateScreenshotBlobPath(
  productId: string,
  feedbackId: string,
  contentType: 'image/png' | 'image/jpeg' | 'image/webp'
): string {
  const screenshotId = `scr_${crypto.randomUUID().split('-')[0]}`;
  const ext = contentType === 'image/png' ? 'png' : contentType === 'image/jpeg' ? 'jpg' : 'webp';
  return `feedback/${productId}/${feedbackId}/${screenshotId}.${ext}`;
}

/**
 * Get feedback with fresh screenshot URL (placeholder - actual SAS generation in blob module).
 * This function validates the feedback exists and has a screenshot.
 */
export async function getFeedbackWithScreenshot(
  id: string,
  productId: string
): Promise<FeedbackDoc | null> {
  const feedback = await getFeedback(id, productId);
  if (!feedback || !feedback.screenshotBlobPath) {
    return null;
  }
  return feedback;
}

/**
 * Check if feedback has screenshot for quick UI checks.
 */
export function hasScreenshot(feedback: FeedbackDoc): boolean {
  return !!feedback.screenshotBlobPath && !!feedback.screenshotContentType;
}

export async function getFeedbackStats(productId: string): Promise<Record<string, number>> {
  const { resources } = await getContainer()
    .items.query<{ type: string; cnt: number }>({
      query: 'SELECT c.type, COUNT(1) AS cnt FROM c WHERE c.productId = @pid GROUP BY c.type',
      parameters: [{ name: '@pid', value: productId }],
    })
    .fetchAll();

  const stats: Record<string, number> = { bug: 0, feature: 0, praise: 0, other: 0, total: 0 };
  for (const r of resources) {
    stats[r.type] = r.cnt;
    stats.total += r.cnt;
  }
  return stats;
}
