import * as admin from 'firebase-admin';
import corsMiddleware from 'cors';
import { HttpsOptions } from 'firebase-functions/v2/https';

try {
  admin.initializeApp();
} catch (e) {
  console.warn('admin.initializeApp() already called or failed:', e);
}

export const db = admin.firestore();
export const storage = admin.storage();
export const FieldValue = admin.firestore.FieldValue;

// --------------------------------------AUTH CONFIGURATION--------------------------------------
export const allowedAdminEmails = ['mooove@nate.com'];

const allowedOrigins = [
  'http://localhost:3001',
  'http://localhost:3000',
  'https://normadbobu.web.app',
  'https://normadbobu.firebaseapp.com',
  'https://normadbobu.com',
];

export const ROLE_THRESHOLD = {
  MASTER: 9,
  ADMIN: 7,
  MANAGER: 5,
  TEACHER: 3,
  USER: 1,
  PUBLIC: 0,
} as const;
export type BoardAccessMode = 'public' | 'private' | 'admin';

export const cookieExpiration = 60 * 60 * 24 * 5 * 1000; // 5 days

// --------------------------------------SERVERS CONFIGURATION--------------------------------------
// Define common settings
const DEFAULT_REGION = 'asia-northeast3';
const DEFAULT_MEMORY = '256MiB';
const STANDARD_MAX_INSTANCES = 1000;
const LOW_TRAFFIC_MAX_INSTANCES = 100;
const DEFAULT_TIMEOUT_SECONDS = 60;

const allowCredentials = true;
export const corsV2Origins = allowedOrigins;

// --- V1/Middleware CORS Configuration (Keep for backward compatibility or specific needs) ---
const corsMiddlewareOptions = {
  origin: function (
    origin: string | undefined,
    callback: (err: Error | null, allow?: boolean) => void,
  ) {
    if (origin === undefined || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      console.warn(`CORS Middleware: Origin '${origin}' not allowed.`);
      callback(new Error('Not allowed by CORS!'));
    }
  },
  credentials: allowCredentials,
};
export const corsMiddlewareHandler = corsMiddleware(corsMiddlewareOptions); // Renamed export
export const commonV2RuntimeOptions: HttpsOptions = {
  region: DEFAULT_REGION,
  memory: DEFAULT_MEMORY,
  maxInstances: STANDARD_MAX_INSTANCES,
  timeoutSeconds: DEFAULT_TIMEOUT_SECONDS,
};

export const lowTrafficV2RuntimeOptions: HttpsOptions = {
  region: DEFAULT_REGION,
  memory: '128MiB',
  maxInstances: LOW_TRAFFIC_MAX_INSTANCES,
  timeoutSeconds: DEFAULT_TIMEOUT_SECONDS,
};

// --------------------------------------UPLOAD SETTINGS--------------------------------------
// Upload Settings
const MAX_FILE_SIZE_MB = 20;
const MAX_TOTAL_FILES = 10;
export const ALLOWED_COLLECTIONS = new Set([
  'notices',
  'projects' /* … */,
] as const);
const ALLOWED_IMAGE_TYPES = [
  'image/jpeg',
  'image/png',
  'image/gif',
  'image/webp',
  'image/jpg',
];
const ALLOWED_VIDEO_TYPES = [
  'video/mp4',
  'video/avi',
  'video/mpeg',
  'video/quicktime',
  'video/x-ms-wmv',
];
export const ALLOWED_DOCUMENT_TYPES = [
  // Word Documents
  'application/msword', // .doc
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
  // Excel Sheets
  'application/vnd.ms-excel', // .xls
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
  // PowerPoint Presentations
  'application/vnd.ms-powerpoint', // .ppt
  'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .pptx
  // PDFs
  'application/pdf',
  // Hangul Word Processor (Korean)
  'application/x-hwp', // .hwp (standardized older type)
  'application/x-hwpx', // .hwpx (newer format)
];

const ALLOWED_FILE_TYPES = [
  ...ALLOWED_IMAGE_TYPES,
  ...ALLOWED_DOCUMENT_TYPES,
  ...ALLOWED_VIDEO_TYPES,
];

const MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024;

const isImageFile = (file: File): boolean =>
  ALLOWED_IMAGE_TYPES.includes(file.type);
const isVideoFile = (file: File): boolean =>
  ALLOWED_VIDEO_TYPES.includes(file.type);
const isDocumentFile = (file: File): boolean =>
  ALLOWED_DOCUMENT_TYPES.includes(file.type);

const isValidFile = (file: File): boolean => {
  return (
    ALLOWED_FILE_TYPES.includes(file.type) && file.size <= MAX_FILE_SIZE_BYTES
  );
};

const getInvalidFileReasonKey = (file: File): string | null => {
  if (!ALLOWED_FILE_TYPES.includes(file.type)) return 'upload.invalid_type';
  if (file.size > MAX_FILE_SIZE_BYTES) return 'upload.exceeds_size';
  return null;
};

// Error Messages
const UploadErrorMessages: Record<string, string> = {
  'upload.invalid_type': '허용되지 않은 파일 형식입니다.',
  'upload.exceeds_size': `파일 크기는 ${MAX_FILE_SIZE_MB}MB 이하만 가능합니다.`,
};
export const CourseCategories = [
  '동료지원가 양성과정',
  '정신건강 바로알기',
  '회복으로 가는 길',
  // '연주',
  // '실용음악',
  // '국악',
  // '융합교육',
  // '프로그램'
] as const;
export const ProgramCategories = [
  '자격증 과정',
  '일반 과정',
  '심화 과정',
] as const;
// Video Providers
export const VideoProviders = ['youtube', 'vimeo', 'unknown'] as const;

// --------------------------------------EXPORT EVERYTHING--------------------------------------
// Export
export const UploadSettings = {
  MAX_FILE_SIZE_MB,
  MAX_TOTAL_FILES,
  MAX_FILE_SIZE_BYTES,
  ALLOWED_FILE_TYPES,
  ALLOWED_IMAGE_TYPES,
  ALLOWED_VIDEO_TYPES,
  ALLOWED_DOCUMENT_TYPES,
  ALLOWED_EXTENSIONS: ALLOWED_FILE_TYPES.join(','),
  cookieExpiration,
  isImageFile,
  isVideoFile,
  isDocumentFile,
  isValidFile,
  getInvalidFileReasonKey,
  UploadErrorMessages,
};
export type CourseCategory = (typeof CourseCategories)[number];
export type ProgramCategory = (typeof ProgramCategories)[number];
export type VideoProvider = (typeof VideoProviders)[number];
