/**
 * Database Schema - Drizzle ORM
 * PostgreSQL schema for A2P AutoPilot tracking system
 */

import { pgTable, text, jsonb, timestamp, integer, pgEnum } from 'drizzle-orm/pg-core';
import { nanoid } from 'nanoid';
import type { SubmissionStatus } from '../types';

// ============================================================
// ENUMS
// ============================================================

export const submissionStatusEnum = pgEnum('submission_status', [
  'pending',
  'creating_profile',
  'profile_submitted',
  'creating_brand',
  'brand_pending',
  'brand_approved',
  'brand_failed',
  'creating_campaign',
  'campaign_pending',
  'campaign_approved',
  'campaign_failed',
  'remediation',
  'manual_review',
  'completed',
]);

export const auditStatusEnum = pgEnum('audit_status', ['success', 'error']);

// ============================================================
// SUBMISSIONS TABLE
// ============================================================

/**
 * Main table tracking each A2P registration through the entire lifecycle
 */
export const submissions = pgTable('submissions', {
  // Primary key - nanoid for URL-safe, collision-resistant IDs
  id: text('id')
    .primaryKey()
    .$defaultFn(() => nanoid()),

  // External reference (e.g. GHL sub-account ID)
  externalId: text('external_id'),

  // Current status in the submission pipeline
  status: submissionStatusEnum('status').notNull().default('pending'),

  // Full input data from user (RegistrationInput type)
  inputData: jsonb('input_data').notNull(),

  // SidChain tracking all Twilio resource SIDs
  sidChain: jsonb('sid_chain').notNull().default('{}'),

  // Generated landing pages
  landingPageUrl: text('landing_page_url'),
  privacyPolicyUrl: text('privacy_policy_url'),
  termsUrl: text('terms_url'),

  // Brand trust score from Twilio (0-100)
  brandTrustScore: integer('brand_trust_score'),

  // Failure tracking
  failureReason: text('failure_reason'),
  attemptCount: integer('attempt_count').notNull().default(0),
  maxAttempts: integer('max_attempts').notNull().default(3),

  // Notification configuration
  notifyWebhook: text('notify_webhook'),
  notifyEmail: text('notify_email'),

  // Timestamps
  createdAt: timestamp('created_at', { mode: 'date' })
    .notNull()
    .defaultNow(),
  updatedAt: timestamp('updated_at', { mode: 'date' })
    .notNull()
    .defaultNow(),
  brandSubmittedAt: timestamp('brand_submitted_at', { mode: 'date' }),
  brandResolvedAt: timestamp('brand_resolved_at', { mode: 'date' }),
  campaignSubmittedAt: timestamp('campaign_submitted_at', { mode: 'date' }),
  campaignResolvedAt: timestamp('campaign_resolved_at', { mode: 'date' }),
  completedAt: timestamp('completed_at', { mode: 'date' }),
});

// ============================================================
// REMEDIATION LOG TABLE
// ============================================================

/**
 * History of automated fixes applied when submissions fail
 */
export const remediationLog = pgTable('remediation_log', {
  id: text('id')
    .primaryKey()
    .$defaultFn(() => nanoid()),

  // Foreign key to submissions
  submissionId: text('submission_id')
    .notNull()
    .references(() => submissions.id, { onDelete: 'cascade' }),

  // What went wrong
  failureReason: text('failure_reason').notNull(),

  // What fix was applied
  fixApplied: text('fix_applied').notNull(),

  // Detailed field changes (before/after)
  fieldsChanged: jsonb('fields_changed').notNull(),

  // When the fix was resubmitted
  resubmittedAt: timestamp('resubmitted_at', { mode: 'date' }).notNull(),

  createdAt: timestamp('created_at', { mode: 'date' })
    .notNull()
    .defaultNow(),
});

// ============================================================
// AUDIT LOG TABLE
// ============================================================

/**
 * Complete audit trail of every Twilio API call made
 */
export const auditLog = pgTable('audit_log', {
  id: text('id')
    .primaryKey()
    .$defaultFn(() => nanoid()),

  // Foreign key to submissions
  submissionId: text('submission_id')
    .notNull()
    .references(() => submissions.id, { onDelete: 'cascade' }),

  // What step was being performed
  stepName: text('step_name').notNull(),

  // Full request/response data
  requestData: jsonb('request_data').notNull(),
  responseData: jsonb('response_data'),

  // Result
  status: auditStatusEnum('status').notNull(),
  errorMessage: text('error_message'),

  // Performance tracking
  durationMs: integer('duration_ms').notNull(),

  createdAt: timestamp('created_at', { mode: 'date' })
    .notNull()
    .defaultNow(),
});

// ============================================================
// TYPE EXPORTS
// ============================================================

export type Submission = typeof submissions.$inferSelect;
export type NewSubmission = typeof submissions.$inferInsert;

export type RemediationLogEntry = typeof remediationLog.$inferSelect;
export type NewRemediationLogEntry = typeof remediationLog.$inferInsert;

export type AuditLogEntry = typeof auditLog.$inferSelect;
export type NewAuditLogEntry = typeof auditLog.$inferInsert;
