/**
 * Hosting Connection Model
 *
 * Per-admin connection to a hosting provider used to publish landing pages, modelled
 * on YouTubeAccount/FacebookAccount (Social Media OS). Each connection is scoped to
 * (companyId, userId) so admins manage their own hosts independently — no cross-admin
 * access.
 *
 * The provider secret (API token, or a JSON blob of SFTP/FTP/S3 credentials) is
 * encrypted at rest via utils/encryption and excluded from queries by default
 * (select: false). Non-secret target metadata (host, remote path, site id, …) is
 * stored in the clear so it can be listed without decrypting.
 *
 * This is entirely additive: no existing model or query references it.
 */

import mongoose, { Schema, Document } from 'mongoose';

export type HostingProvider =
  | 'sftp'
  | 'ftp'
  | 'netlify'
  | 'vercel'
  | 'cloudflare-pages'
  | 'github-pages'
  | 's3'
  | 'wordpress';

export type HostingConnectionStatus = 'connected' | 'reconnect_required' | 'revoked';

export interface IHostingConnection extends Document {
  companyId: string;
  userId: string; // owning admin — all access is scoped to this user
  provider: HostingProvider;
  label: string;

  // Encrypted secret material (never returned by default queries).
  // Holds the API token, or a JSON string of credentials for SFTP/FTP/S3.
  encryptedSecret?: string;

  // Non-secret target metadata (provider-specific; only relevant fields populated)
  host?: string;
  port?: number;
  username?: string;
  remotePath?: string;   // SFTP/FTP target dir, e.g. public_html
  baseUrl?: string;      // user-declared public URL (SFTP/FTP can't detect it)
  siteId?: string;       // Netlify/Vercel/Cloudflare site/project id
  teamId?: string;       // Vercel team / CF account id
  repo?: string;         // GitHub owner/repo
  branch?: string;       // GitHub Pages branch
  region?: string;       // S3 region
  bucket?: string;       // S3 bucket
  providerData?: Record<string, any>; // Provider-specific data (e.g. WordPress page IDs)

  status: HostingConnectionStatus;
  lastError?: string;
  connectedAt: Date;
  lastUsedAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}

const HostingConnectionSchema = new Schema<IHostingConnection>({
  companyId: { type: String, required: [true, 'Company ID is required'], index: true },
  userId: { type: String, required: [true, 'User ID is required'], index: true },
  provider: {
    type: String,
    enum: ['sftp', 'ftp', 'netlify', 'vercel', 'cloudflare-pages', 'github-pages', 's3', 'wordpress'],
    required: [true, 'Provider is required'],
  },
  label: { type: String, required: [true, 'Label is required'] },

  // Encrypted secret — never returned by default queries
  encryptedSecret: { type: String, select: false },

  host: { type: String },
  port: { type: Number },
  username: { type: String },
  remotePath: { type: String },
  baseUrl: { type: String },
  siteId: { type: String },
  teamId: { type: String },
  repo: { type: String },
  branch: { type: String },
  region: { type: String },
  bucket: { type: String },
  providerData: { type: Schema.Types.Mixed, default: {} },

  status: {
    type: String,
    enum: ['connected', 'reconnect_required', 'revoked'],
    default: 'connected',
  },
  lastError: { type: String },
  connectedAt: { type: Date, default: Date.now },
  lastUsedAt: { type: Date, default: null },
}, {
  timestamps: true,
});

HostingConnectionSchema.index({ companyId: 1, userId: 1 });

export const HostingConnection =
  mongoose.models.HostingConnection || mongoose.model<IHostingConnection>('HostingConnection', HostingConnectionSchema);
