const { DataTypes } = require("sequelize");

module.exports = (sequelize) => {
	const Prescription = sequelize.define(
		"prescription",
		{
			id: {
				type: DataTypes.INTEGER,
				autoIncrement: true,
				primaryKey: true,
			},
			creation: { type: DataTypes.DATE, allowNull: false },
			modified: { type: DataTypes.DATE, allowNull: false },
			modified_by: { type: DataTypes.INTEGER, allowNull: false },
			owner: { type: DataTypes.INTEGER, allowNull: false }, // User or doctor who owns the record

			// Prescription specific fields
			prescription_no: { type: DataTypes.STRING(100), allowNull: true }, // Nomor resep unik

			notes: { type: DataTypes.TEXT, allowNull: true }, // Catatan tambahan
			source: { type: DataTypes.STRING(50), allowNull: true }, // Sumber resep, misal: "Dokter", "Apotek", dll.
			prescription_date: { type: DataTypes.DATEONLY, allowNull: false }, // Tanggal resep dibuat

			patient_id: { type: DataTypes.INTEGER, allowNull: false }, // FK ke pasien/User
			doctor_id: { type: DataTypes.INTEGER, allowNull: true }, // FK ke dokter yang membuat resep
		},
		{
			tableName: "prescriptions",
			freezeTableName: true,
		}
	);

	/**
	 * Associates the Prescription model with other models.
	 * @param {object} models - The models to associate with.
	 */
	Prescription.associate = (models) => {
		Prescription.belongsTo(models.Patient, { foreignKey: "patient_id", as: "patient" });
		Prescription.belongsTo(models.Doctor, { foreignKey: "doctor_id", as: "doctor" });
		Prescription.hasMany(models.PrescriptionMedicine, { foreignKey: "prescription_id", as: "prescriptionmedicines" });
	};

	return Prescription;
};
