/**
 * LibraryIcon Model
 *
 * Central repository of reusable application icons managed exclusively by the
 * Super Admin. Icons are stored as ICON CODE (not uploaded image files): raw SVG
 * markup, or an icon-library class/name (Font Awesome, Bootstrap Icons, Material
 * Icons, Lucide, Heroicons, Remix Icons, or a custom value). The stored code is
 * rendered anywhere in the app via the shared LibraryIcon renderer.
 *
 * Any authenticated user may READ these icons (to select one); only Super Admins
 * may create/update/delete them (enforced in routes/library.ts).
 *
 * `checksum` is a SHA-256 of `iconType + '\n' + iconCode` and carries a unique
 * index — it prevents storing the exact same icon code twice.
 */

import mongoose, { Schema, Document } from 'mongoose';

export type LibraryIconType =
  | 'svg'
  | 'font-awesome'
  | 'bootstrap'
  | 'material'
  | 'heroicons'
  | 'lucide'
  | 'remix'
  | 'custom';

export const LIBRARY_ICON_TYPES: LibraryIconType[] = [
  'svg',
  'font-awesome',
  'bootstrap',
  'material',
  'heroicons',
  'lucide',
  'remix',
  'custom',
];

export interface ILibraryIcon extends Document {
  /** Display name of the icon */
  name: string;
  /** Free-form search tags */
  tags: string[];
  /** Which icon system the code belongs to */
  iconType: LibraryIconType;
  /** The exact icon code entered by the admin (SVG markup or icon class/name) */
  iconCode: string;
  /** SHA-256 of `iconType + '\n' + iconCode` — used for duplicate detection */
  checksum: string;
  /** User id of the super-admin who created it */
  uploadedBy: string;
  /** Email of the creator (for display/audit) */
  uploadedByEmail?: string;
  createdAt: Date;
  updatedAt: Date;
}

const libraryIconSchema = new Schema<ILibraryIcon>(
  {
    name: {
      type: String,
      required: true,
      trim: true,
      index: true,
    },
    tags: {
      type: [String],
      default: [],
      index: true,
    },
    iconType: {
      type: String,
      enum: LIBRARY_ICON_TYPES,
      required: true,
      index: true,
    },
    iconCode: {
      type: String,
      required: true,
    },
    checksum: {
      type: String,
      required: true,
      // Unique so the exact same icon code cannot be stored twice.
      unique: true,
      index: true,
    },
    uploadedBy: {
      type: String,
      required: true,
    },
    uploadedByEmail: {
      type: String,
      default: '',
    },
  },
  {
    timestamps: true,
  },
);

// Prevent model overwrite in dev (hot reload)
export const LibraryIcon =
  mongoose.models.LibraryIcon || mongoose.model<ILibraryIcon>('LibraryIcon', libraryIconSchema);
