import { randomUUID } from 'node:crypto';
import { S3Client, PutObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3';
// (GetObjectCommand is imported below, next to the download presign.)
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { env, uploadAllowedMime } from '../../config/env';
import { BadRequestError } from '../../lib/errors';

const EXT_BY_MIME: Record<string, string> = {
  'image/jpeg': 'jpg',
  'image/png': 'png',
  'application/pdf': 'pdf',
};

let client: S3Client | null = null;
function s3(): S3Client {
  if (!env.S3_BUCKET_NAME || !env.AWS_ACCESS_KEY_ID || !env.AWS_SECRET_ACCESS_KEY) {
    throw new BadRequestError('File uploads are not configured (missing S3 settings)', 'S3_NOT_CONFIGURED');
  }
  if (!client) {
    client = new S3Client({
      region: env.AWS_REGION,
      credentials: { accessKeyId: env.AWS_ACCESS_KEY_ID, secretAccessKey: env.AWS_SECRET_ACCESS_KEY },
    });
  }
  return client;
}

/** Where each kind of upload lives under the tenant's prefix. */
const PREFIX: Record<UploadKind, string> = {
  ID_PROOF: 'students/id_proof',
  PHOTO: 'students/photo',
  PROPERTY_LOGO: 'properties/logo',
  BILLING_LOGO: 'billing/logo',
  ADDRESS_PROOF: 'students/address_proof',
  POLICE_VERIFICATION: 'students/police_verification',
  ASSET_PHOTO: 'rooms/asset_photos',
  PROPERTY_PHOTO: 'properties/photos',
  VISITOR_PHOTO: 'visitors/photo',
  ATTACHMENT: 'attachments',
};

// ATTACHMENT is uploaded only through /api/attachments, which checks the record it belongs to.
export type UploadKind = 'ID_PROOF' | 'PHOTO' | 'PROPERTY_LOGO' | 'BILLING_LOGO' | 'ADDRESS_PROOF' | 'POLICE_VERIFICATION' | 'ASSET_PHOTO' | 'VISITOR_PHOTO' | 'PROPERTY_PHOTO' | 'ATTACHMENT';

/**
 * Issue a short-lived presigned PUT URL for a tenant file.
 * Server-side validation (type + declared size) happens BEFORE the URL is
 * issued, and ContentType is pinned into the signature so the client must
 * upload exactly what it declared.
 */
export async function presignStudentUpload(params: {
  tenantId: string;
  kind: UploadKind;
  contentType: string;
  contentLength: number;
}): Promise<{ uploadUrl: string; key: string }> {
  if (!uploadAllowedMime.includes(params.contentType)) {
    throw new BadRequestError(`Unsupported file type. Allowed: ${uploadAllowedMime.join(', ')}`);
  }
  // A logo is rendered in an <img>; a PDF there would simply not display.
  if ((params.kind === 'PROPERTY_LOGO' || params.kind === 'BILLING_LOGO' || params.kind === 'PROPERTY_PHOTO') && !params.contentType.startsWith('image/')) {
    throw new BadRequestError('A logo must be an image (JPG or PNG)');
  }
  if (params.contentLength <= 0 || params.contentLength > env.UPLOAD_MAX_BYTES) {
    throw new BadRequestError(`File too large. Max ${Math.floor(env.UPLOAD_MAX_BYTES / 1024 / 1024)} MB`);
  }

  const ext = EXT_BY_MIME[params.contentType] ?? 'bin';
  const key = `tenants/${params.tenantId}/${PREFIX[params.kind]}/${randomUUID()}.${ext}`;

  const uploadUrl = await getSignedUrl(
    s3(),
    new PutObjectCommand({ Bucket: env.S3_BUCKET_NAME, Key: key, ContentType: params.contentType }),
    { expiresIn: 300 },
  );
  return { uploadUrl, key };
}

import { GetObjectCommand } from '@aws-sdk/client-s3';

/**
 * A short-lived READ url for a file this tenant owns.
 *
 * The key prefix is the authorisation: everything uploaded through the presign
 * flow lives under tenants/{tenantId}/…, so a key outside the caller's own
 * prefix is refused before S3 is ever asked.
 */
export async function presignDownload(tenantId: string, key: string): Promise<string> {
  if (!key.startsWith(`tenants/${tenantId}/`)) {
    throw new BadRequestError('That file does not belong to this account');
  }
  return getSignedUrl(s3(), new GetObjectCommand({ Bucket: env.S3_BUCKET_NAME, Key: key }), { expiresIn: 600 });
}

/**
 * The bytes of a file this tenant owns, for server-side rendering (the logo
 * on an invoice PDF). Same prefix rule as `presignDownload`. Returns null on
 * any failure — a document without its logo beats no document.
 */
export async function getTenantFileBytes(tenantId: string, key: string): Promise<Buffer | null> {
  if (!key.startsWith(`tenants/${tenantId}/`)) return null;
  if (!env.S3_BUCKET_NAME || !env.AWS_ACCESS_KEY_ID || !env.AWS_SECRET_ACCESS_KEY) return null;
  try {
    const out = await s3().send(new GetObjectCommand({ Bucket: env.S3_BUCKET_NAME, Key: key }));
    const bytes = await out.Body?.transformToByteArray();
    return bytes ? Buffer.from(bytes) : null;
  } catch {
    return null;
  }
}

/**
 * Upload a file THROUGH the API instead of straight to S3.
 *
 * The presigned-PUT flow needs the S3 bucket to allow the browser's origin in
 * its CORS policy — and when it doesn't, the upload dies in preflight with no
 * server-side trace. Server-to-S3 has no CORS at all, and at logo/photo sizes
 * the API relaying a few megabytes is a fair price for uploads that work from
 * any origin with zero bucket configuration.
 */
export async function uploadDirect(params: {
  tenantId: string;
  kind: UploadKind;
  contentType: string;
  body: Buffer;
}): Promise<{ key: string }> {
  if (!uploadAllowedMime.includes(params.contentType)) {
    throw new BadRequestError(`Unsupported file type. Allowed: ${uploadAllowedMime.join(', ')}`);
  }
  if ((params.kind === 'PROPERTY_LOGO' || params.kind === 'BILLING_LOGO' || params.kind === 'PROPERTY_PHOTO') && !params.contentType.startsWith('image/')) {
    throw new BadRequestError('A logo must be an image (JPG or PNG)');
  }
  if (params.body.length === 0 || params.body.length > env.UPLOAD_MAX_BYTES) {
    throw new BadRequestError(`File too large. Max ${Math.floor(env.UPLOAD_MAX_BYTES / 1024 / 1024)} MB`);
  }

  const ext = EXT_BY_MIME[params.contentType] ?? 'bin';
  const key = `tenants/${params.tenantId}/${PREFIX[params.kind]}/${randomUUID()}.${ext}`;
  await s3().send(
    new PutObjectCommand({ Bucket: env.S3_BUCKET_NAME, Key: key, ContentType: params.contentType, Body: params.body }),
  );
  return { key };
}

// ── Platform files (the website blog's images, docs/blog-cms-plan.md) ────────
// Not a tenant's: they live under platform/website-blog/, outside every
// tenants/{id}/ prefix, so no tenant presign can ever reach them, and these
// helpers refuse any key outside that prefix.

export const BLOG_MEDIA_PREFIX = 'platform/website-blog/';

function assertBlogKey(key: string) {
  if (!key.startsWith(BLOG_MEDIA_PREFIX) || key.includes('..')) {
    throw new BadRequestError('That file is not a blog image');
  }
}

/** Store one blog image. The bucket stays private. */
export async function putBlogObject(key: string, body: Buffer, contentType: string): Promise<void> {
  assertBlogKey(key);
  await s3().send(new PutObjectCommand({ Bucket: env.S3_BUCKET_NAME, Key: key, ContentType: contentType, Body: body }));
}

/** A short-lived read link: for the editor's preview, and for the website build. */
export async function presignBlogObject(key: string, seconds = 600): Promise<string> {
  assertBlogKey(key);
  return getSignedUrl(s3(), new GetObjectCommand({ Bucket: env.S3_BUCKET_NAME, Key: key }), { expiresIn: seconds });
}

/** Remove a blog image. Best effort: a stray object costs pennies, a thrown error a page. */
export async function deleteBlogObject(key: string): Promise<void> {
  assertBlogKey(key);
  try {
    await s3().send(new DeleteObjectCommand({ Bucket: env.S3_BUCKET_NAME, Key: key }));
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error(`[blog] could not delete ${key}: ${err instanceof Error ? err.message : String(err)}`);
  }
}

// ── The bug tracker's files (docs/bug-tracker-plan.md) ──────────────────────
// Screenshots, PDFs and logs on bugs and comments. Platform files like the
// blog's: under platform/bug-tracker/, outside every tenants/{id}/ prefix, and
// these helpers refuse any key outside it. They may show production data, so
// they are only ever read through a short-lived link.

export const BUG_FILES_PREFIX = 'platform/bug-tracker/';

function assertBugKey(key: string) {
  if (!key.startsWith(BUG_FILES_PREFIX) || key.includes('..')) {
    throw new BadRequestError('That file is not a bug tracker file');
  }
}

export async function putBugObject(key: string, body: Buffer, contentType: string): Promise<void> {
  assertBugKey(key);
  await s3().send(new PutObjectCommand({ Bucket: env.S3_BUCKET_NAME, Key: key, ContentType: contentType, Body: body }));
}

/**
 * A ten-minute read link. An image opens in the page; anything else is
 * downloaded under its own name rather than opened by the browser.
 */
export async function presignBugObject(key: string, opts: { filename: string; inline: boolean }): Promise<string> {
  assertBugKey(key);
  const safeName = opts.filename.replace(/[^\w.\- ]+/g, '_').slice(0, 120) || 'file';
  return getSignedUrl(
    s3(),
    new GetObjectCommand({
      Bucket: env.S3_BUCKET_NAME,
      Key: key,
      ResponseContentDisposition: `${opts.inline ? 'inline' : 'attachment'}; filename="${safeName}"`,
    }),
    { expiresIn: 600 },
  );
}

/** Best effort, like the blog's: a stray object costs pennies, a thrown error a page. */
export async function deleteBugObject(key: string): Promise<void> {
  assertBugKey(key);
  try {
    await s3().send(new DeleteObjectCommand({ Bucket: env.S3_BUCKET_NAME, Key: key }));
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error(`[bugs] could not delete ${key}: ${err instanceof Error ? err.message : String(err)}`);
  }
}
