import { v4 as uuid } from 'uuid';
import { Op, type QueryInterface } from 'sequelize';
import {
  SEED_ORGANIZATION_ID,
  SEED_CAMPUS_ID,
  SEED_FIXTURE_USERS,
} from '@/shared/constants/seed-fixtures';
import {
  POLICY_DOCUMENT_CATEGORIES,
  type PolicyDocumentCategory,
} from '@/shared/constants/policy-documents';
import { formatPersonName } from '@/shared/constants/users';
import { CONTENT_CATALOG_SEED_PAYLOADS } from './content-catalog-data/content-catalog-seed-payloads';

/**
 * Seeds the unified `policy_documents` for the Safety Protocols and Handbook &
 * Policies pages (Workstream 11). Safety protocols reuse the existing
 * content-catalog `safetyProtocols` payload (steps + autism considerations);
 * a few handbook policies give the handbook page demo content. Authored by the
 * seeded director on the primary org/campus. Idempotent by `importHash`.
 */
const DIRECTOR = SEED_FIXTURE_USERS.find((u) => u.role === 'director');
const AUTHOR = DIRECTOR
  ? formatPersonName(DIRECTOR.namePrefix, DIRECTOR.firstName, DIRECTOR.lastName)
  : null;
const AUTHOR_ID = DIRECTOR?.id ?? null;

interface SeedRow {
  readonly importHash: string;
  readonly title: string;
  readonly category: PolicyDocumentCategory;
  readonly tag: string;
  readonly body: string | null;
  readonly steps: readonly string[] | null;
  readonly autismConsiderations: readonly string[] | null;
}

const SAFETY_ROWS: SeedRow[] = CONTENT_CATALOG_SEED_PAYLOADS.safetyProtocols.map(
  (protocol) => ({
    importHash: `policy-doc-safety-${protocol.id}`,
    title: protocol.title,
    category: POLICY_DOCUMENT_CATEGORIES.SAFETY_PROTOCOL,
    tag: protocol.iconId,
    body: null,
    steps: protocol.steps,
    autismConsiderations: protocol.autismConsiderations,
  }),
);

const HANDBOOK_ROWS: SeedRow[] = [
  {
    importHash: 'policy-doc-handbook-behavior',
    title: 'Student Behavior Intervention Policy',
    category: POLICY_DOCUMENT_CATEGORIES.HANDBOOK_POLICY,
    tag: 'Behavior',
    body: 'All behavior interventions must follow the least-restrictive approach. Staff must document all incidents using the Behavior Incident Report form within 24 hours. Physical intervention is only permitted when there is imminent danger to the individual or others, and must follow de-escalation protocols. All physical interventions must be reported to administration immediately.',
    steps: null,
    autismConsiderations: null,
  },
  {
    importHash: 'policy-doc-handbook-attendance',
    title: 'Attendance & Tardiness Policy',
    category: POLICY_DOCUMENT_CATEGORIES.HANDBOOK_POLICY,
    tag: 'Operations',
    body: 'Staff record campus attendance daily by 9:00 AM. Tardiness beyond 15 minutes requires a note to the office manager. Patterns of absence are reviewed monthly with the director.',
    steps: null,
    autismConsiderations: null,
  },
  {
    importHash: 'policy-doc-handbook-parent-comm',
    title: 'Parent Communication Standards',
    category: POLICY_DOCUMENT_CATEGORIES.HANDBOOK_POLICY,
    tag: 'Communication',
    body: 'Use plain, respectful language with families. Acknowledge messages within one business day. Document significant conversations in the communication log.',
    steps: null,
    autismConsiderations: null,
  },
  {
    importHash: 'policy-doc-handbook-prof-dev',
    title: 'Professional Development Requirements',
    category: POLICY_DOCUMENT_CATEGORIES.HANDBOOK_POLICY,
    tag: 'Professional Growth',
    body: 'All instructional staff complete 20 hours of professional development annually, including at least 6 hours on autism-specific practices and de-escalation.',
    steps: null,
    autismConsiderations: null,
  },
];

const ALL_ROWS = [...SAFETY_ROWS, ...HANDBOOK_ROWS];

export default {
  up: async (queryInterface: QueryInterface) => {
    const now = new Date();
    const importHashes = ALL_ROWS.map((row) => row.importHash);

    await queryInterface.bulkDelete('policy_documents', {
      importHash: { [Op.in]: importHashes },
    });

    const rows = ALL_ROWS.map((row) => ({
      id: uuid(),
      title: row.title,
      body: row.body,
      category: row.category,
      tag: row.tag,
      author: AUTHOR,
      // JSONB columns: serialize for bulkInsert (Postgres casts JSON → jsonb).
      steps: row.steps ? JSON.stringify(row.steps) : null,
      autism_considerations: row.autismConsiderations
        ? JSON.stringify(row.autismConsiderations)
        : null,
      version: 1,
      active: true,
      importHash: row.importHash,
      organizationId: SEED_ORGANIZATION_ID,
      campusId: SEED_CAMPUS_ID,
      createdById: AUTHOR_ID,
      updatedById: AUTHOR_ID,
      createdAt: now,
      updatedAt: now,
    }));

    await queryInterface.bulkInsert('policy_documents', rows);
  },

  down: async (queryInterface: QueryInterface) => {
    await queryInterface.bulkDelete('policy_documents', {
      importHash: { [Op.in]: ALL_ROWS.map((row) => row.importHash) },
    });
  },
};
