const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Sub-schema: File Info
const FileInfoSchema = new Schema({
  path: { type: String, required: true },
  url: { type: String },
  thumbnailPath: { type: String },
  thumbnailUrl: { type: String },
  originalName: { type: String },
  mimeType: { type: String, required: true },
  size: { type: Number }, // bytes
  dimensions: {
    width: { type: Number },
    height: { type: Number }
  }
}, { _id: false });

// Sub-schema: AI Generation Params
const AiGenerationSchema = new Schema({
  prompt: { type: String, required: true },
  negativePrompt: { type: String },
  provider: { 
    type: String, 
    required: true,
    enum: ['hf', 'fal', 'ideogram', 'openai', 'stability', 'midjourney']
  },
  model: { type: String },
  seed: { type: Number },
  steps: { type: Number },
  cfg: { type: Number },
  requestedSize: { type: String },
  actualSize: { type: String },
  aspectRatio: { type: String },
  styleType: { type: String },
  generationTime: { type: Number }, // ms
  cost: { type: Number, default: 0 },
  rawResponse: { type: Schema.Types.Mixed }
}, { _id: false });

// Sub-schema: Usage Tracking
const UsageTrackingSchema = new Schema({
  usedInPosters: [{ type: Schema.Types.ObjectId, ref: 'Poster' }],
  usedInTemplates: [{ type: Schema.Types.ObjectId, ref: 'Template' }],
  usageCount: { type: Number, default: 0 }
}, { _id: false });

// Sub-schema: Asset Metadata
const AssetMetadataSchema = new Schema({
  userId: { type: Schema.Types.ObjectId, ref: 'User', index: true },
  projectId: { type: Schema.Types.ObjectId, ref: 'Project' },
  tags: [{ type: String }],
  description: { type: String },
  isReusable: { type: Boolean, default: true },
  isPublic: { type: Boolean, default: false }
}, { _id: false });

// MAIN SCHEMA: Asset
const AssetSchema = new Schema({
  type: { 
    type: String, 
    required: true,
    enum: ['image', 'logo', 'icon', 'font']
  },
  category: { 
    type: String, 
    required: true,
    enum: ['background', 'main', 'logo', 'decoration', 'overlay', 'other'],
    index: true
  },
  sourceType: { 
    type: String, 
    required: true,
    enum: ['upload', 'ai', 'library', 'url'],
    index: true
  },
  
  file: { type: FileInfoSchema, required: true },
  aiGeneration: { type: AiGenerationSchema },
  
  usage: { type: UsageTrackingSchema, default: () => ({}) },
  metadata: { type: AssetMetadataSchema, default: () => ({}) },
  
  status: {
    type: String,
    enum: ['processing', 'ready', 'error', 'deleted'],
    default: 'ready'
  },
  errorMessage: { type: String }
}, {
  timestamps: true,
  toJSON: { virtuals: true }
});

// Indexes
AssetSchema.index({ 'metadata.userId': 1, category: 1 });
AssetSchema.index({ 'metadata.tags': 1 });
AssetSchema.index({ sourceType: 1, status: 1 });

// Virtual: isAiGenerated
AssetSchema.virtual('isAiGenerated').get(function() {
  return this.sourceType === 'ai';
});

// Methods
AssetSchema.methods.addUsage = async function(posterId, type = 'poster') {
  if (type === 'poster' && !this.usage.usedInPosters.includes(posterId)) {
    this.usage.usedInPosters.push(posterId);
  } else if (type === 'template' && !this.usage.usedInTemplates.includes(posterId)) {
    this.usage.usedInTemplates.push(posterId);
  }
  this.usage.usageCount = this.usage.usedInPosters.length + this.usage.usedInTemplates.length;
  return this.save();
};

AssetSchema.methods.getPublicUrl = function() {
  return this.file.url || `/api/assets/${this._id}/file`;
};

// Statics
AssetSchema.statics.findByUser = function(userId, category = null) {
  const query = { 'metadata.userId': userId, status: 'ready' };
  if (category) query.category = category;
  return this.find(query).sort({ createdAt: -1 });
};

AssetSchema.statics.findReusable = function(userId, category = null) {
  const query = { 
    'metadata.userId': userId, 
    'metadata.isReusable': true,
    status: 'ready'
  };
  if (category) query.category = category;
  return this.find(query).sort({ 'usage.usageCount': -1 });
};

module.exports = mongoose.model('Asset', AssetSchema);