import { Model, DataTypes, Sequelize } from 'sequelize';

/**
 * Migration
 * -----------
 * Tracks which database migrations have been applied to this environment.
 *
 * Workflow:
 *   - `npm run migrate`          -> destructive fresh sync (drops everything and
 *                                   recreates schema from Sequelize models).
 *   - `npm run migrate:baseline` -> stamps every existing migration file under
 *                                   `scripts/migrations/` as already-applied
 *                                   (use this immediately after a fresh sync so
 *                                   future incremental runs don't re-execute
 *                                   them on top of an already-correct schema).
 *   - `npm run migrate:up`       -> applies any migration file under
 *                                   `scripts/migrations/` that is not yet
 *                                   recorded in this table.
 *   - `npm run migrate:status`   -> lists applied vs pending migrations.
 *   - `npm run migrate:create`   -> scaffolds a new `<ts>_<name>.ts` file.
 *
 * `name` is the canonical filename (without extension) so it remains stable
 * even if the file is moved between directories.
 */
export interface MigrationAttributes {
    id: string;
    name: string;
    appliedAt: Date;
    checksum: string | null;
}

export interface MigrationInstance
    extends Model<MigrationAttributes>,
    MigrationAttributes { }

export default (sequelize: Sequelize) => {
    const Migration = sequelize.define<MigrationInstance>(
        'Migration',
        {
            id: {
                type: DataTypes.UUID,
                defaultValue: DataTypes.UUIDV4,
                primaryKey: true
            },
            name: {
                type: DataTypes.STRING(255),
                allowNull: false,
                unique: true
            },
            appliedAt: {
                type: DataTypes.DATE,
                allowNull: false,
                defaultValue: DataTypes.NOW
            },
            checksum: {
                // Optional SHA-256 of the migration file contents, useful to detect
                // edits to an already-applied migration during code review.
                type: DataTypes.STRING(64),
                allowNull: true
            }
        },
        {
            tableName: 'migrations',
            timestamps: false,
            indexes: [
                { unique: true, fields: ['name'] },
                { fields: ['appliedAt'] }
            ]
        }
    );

    return Migration;
};
