/**
 * GMB Location Model
 * Google Business Profile location management with connection, verification, and stats
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// TYPE DEFINITIONS
// ============================================

export type ConnectionStatus = 'connected' | 'disconnected' | 'pending' | 'error';
export type VerificationStatus = 'verified' | 'unverified' | 'pending' | 'suspended';
export type LocationStatus = 'active' | 'inactive' | 'draft';
export type PublishStatus = 'draft' | 'publishing' | 'published' | 'failed' | 'sync_required';
export type SyncState = 'synced' | 'local_ahead' | 'remote_ahead' | 'conflict';

// ============================================
// MAIN INTERFACE
// ============================================

export interface IGmbLocation extends Document {
  // A. Google Account
  googleAccountId?: string;
  googleAccountEmail?: string;
  connectionStatus: ConnectionStatus;
  connectedAt?: Date;
  lastSyncedAt?: Date;

  // B. Business Info
  locationName: string;
  primaryPhone?: string;
  website?: string;
  description?: string;
  shortDescription?: string;
  category?: string;
  categories: string[];

  // C. Address
  streetAddress?: string;
  city?: string;
  region?: string;
  postalCode?: string;
  country?: string;
  latitude?: number;
  longitude?: number;

  // D. Hours
  regularHours: Record<string, unknown>;
  specialHours: Record<string, unknown>[];
  alwaysOpen: boolean;

  // E. Service & Attributes
  serviceAreas: string[];
  attributes: Record<string, unknown>[];

  // E2. Rich profile sections (AI-generated Google Business Profile content)
  services: Record<string, unknown>[];
  products: Record<string, unknown>[];
  faqs: Record<string, unknown>[];
  highlights: string[];
  businessPosts: Record<string, unknown>[];
  reviewResponseTemplates: Record<string, unknown>;
  /** Complete Google-ready profile (saved data + generated content) for review/copy. */
  generatedProfile?: Record<string, unknown>;

  // F. Verification
  verificationStatus: VerificationStatus;
  verificationMethod?: string;

  // G. Media
  logoUrl?: string;
  coverPhotoUrl?: string;
  photos: string[];
  media: string[];
  videoUrls: string[];

  // H. Status
  status: LocationStatus;
  isPrimary: boolean;

  // I. Google IDs
  locationId?: string;
  placeId?: string;

  // J. URLs
  appointmentUrl?: string;
  menuUrl?: string;
  bookingUrl?: string;

  // J2. Social profiles
  socialProfiles?: Record<string, string>;

  // K. Stats
  totalReviews: number;
  averageRating: number;
  totalPosts: number;
  totalPhotos: number;

  // L. Company Reference
  companyId: string;

  // M2. Data sources the AI generation draws on (same shape as WhatsApp Nurturing)
  dataSources: string[];
  linkedData: Record<string, unknown>;

  // M. AI generation metadata (set when the profile is generated from business context)
  aiGenerated?: boolean;
  aiGeneratedAt?: Date;
  aiModel?: string;
  aiProvider?: string;

  // N. Publishing — Google Business Profile integration
  publishStatus: PublishStatus;
  publishedAt?: Date;
  publishError?: string;
  googleLocationId?: string;        // Google's location resource name (e.g., "locations/1234567890")
  googleResourceName?: string;       // Full resource name (e.g., "accounts/123/locations/456")
  lastGoogleSyncAt?: Date;
  syncState: SyncState;

  // Timestamps
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// MAIN SCHEMA
// ============================================

const GmbLocationSchema = new Schema<IGmbLocation>({
  // A. Google Account
  googleAccountId: String,
  googleAccountEmail: String,
  connectionStatus: {
    type: String,
    enum: ['connected', 'disconnected', 'pending', 'error'],
    default: 'disconnected'
  },
  connectedAt: Date,
  lastSyncedAt: Date,

  // B. Business Info
  locationName: {
    type: String,
    required: [true, 'Location name is required'],
    trim: true
  },
  primaryPhone: String,
  website: String,
  description: String,
  shortDescription: String,
  category: String,
  categories: [String],

  // C. Address
  streetAddress: String,
  city: String,
  region: String,
  postalCode: String,
  country: String,
  latitude: Number,
  longitude: Number,

  // D. Hours
  regularHours: {
    type: Schema.Types.Mixed,
    default: {}
  },
  specialHours: [Schema.Types.Mixed],
  alwaysOpen: {
    type: Boolean,
    default: false
  },

  // E. Service & Attributes
  serviceAreas: [String],
  attributes: [Schema.Types.Mixed],

  // E2. Rich profile sections (AI-generated Google Business Profile content)
  services: [Schema.Types.Mixed],
  products: [Schema.Types.Mixed],
  faqs: [Schema.Types.Mixed],
  highlights: [String],
  businessPosts: [Schema.Types.Mixed],
  reviewResponseTemplates: {
    type: Schema.Types.Mixed,
    default: {}
  },
  generatedProfile: Schema.Types.Mixed,

  // F. Verification
  verificationStatus: {
    type: String,
    enum: ['verified', 'unverified', 'pending', 'suspended'],
    default: 'unverified'
  },
  verificationMethod: String,

  // G. Media
  logoUrl: String,
  coverPhotoUrl: String,
  photos: [String],
  media: [String],
  videoUrls: [String],

  // H. Status
  status: {
    type: String,
    enum: ['active', 'inactive', 'draft'],
    default: 'active'
  },
  isPrimary: {
    type: Boolean,
    default: false
  },

  // I. Google IDs
  locationId: String,
  placeId: String,

  // J. URLs
  appointmentUrl: String,
  menuUrl: String,
  bookingUrl: String,

  // J2. Social profiles
  socialProfiles: {
    type: Schema.Types.Mixed,
    default: {}
  },

  // K. Stats
  totalReviews: {
    type: Number,
    default: 0
  },
  averageRating: {
    type: Number,
    default: 0
  },
  totalPosts: {
    type: Number,
    default: 0
  },
  totalPhotos: {
    type: Number,
    default: 0
  },

  // L. Company Reference
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true
  },

  // M2. Data sources the AI generation draws on
  dataSources: [String],
  linkedData: {
    type: Schema.Types.Mixed,
    default: {}
  },

  // M. AI generation metadata
  aiGenerated: {
    type: Boolean,
    default: false
  },
  aiGeneratedAt: Date,
  aiModel: String,
  aiProvider: String,

  // N. Publishing — Google Business Profile integration
  publishStatus: {
    type: String,
    enum: ['draft', 'publishing', 'published', 'failed', 'sync_required'],
    default: 'draft',
  },
  publishedAt: Date,
  publishError: String,
  googleLocationId: String,
  googleResourceName: String,
  lastGoogleSyncAt: Date,
  syncState: {
    type: String,
    enum: ['synced', 'local_ahead', 'remote_ahead', 'conflict'],
    default: 'synced',
  },

}, {
  timestamps: true
});

// ============================================
// INDEXES
// ============================================

GmbLocationSchema.index({ companyId: 1 });
GmbLocationSchema.index({ isPrimary: 1 });

// One published Business Profile per Google Account per company — enforces
// the 1:1 rule: one Google account can only have one published profile, and
// one profile can only be published to one Google account.
GmbLocationSchema.index(
  { companyId: 1, googleAccountId: 1 },
  { unique: true, partialFilterExpression: { publishStatus: { $in: ['published', 'publishing'] } } }
);

// ============================================
// EXPORT
// ============================================

export const GmbLocation = mongoose.models.GmbLocation || mongoose.model<IGmbLocation>('GmbLocation', GmbLocationSchema);