import { DataTypes, Model, Optional } from 'sequelize';
import { sequelize } from '../config/database';
import RequestSummary from './RequestSummary';
import { User } from './User';

interface SharedSummaryAttributes {
  sharedSummaryId: string;
  summaryId: string;
  sharedBy: string;
  sharedWith: string;
  sharedAt: Date;
  viewedAt: Date | null;
  isRead: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}

interface SharedSummaryCreationAttributes
  extends Optional<SharedSummaryAttributes, 'sharedSummaryId' | 'sharedAt' | 'viewedAt' | 'isRead' | 'createdAt' | 'updatedAt'> {}

class SharedSummary extends Model<SharedSummaryAttributes, SharedSummaryCreationAttributes>
  implements SharedSummaryAttributes {
  public sharedSummaryId!: string;
  public summaryId!: string;
  public sharedBy!: string;
  public sharedWith!: string;
  public sharedAt!: Date;
  public viewedAt!: Date | null;
  public isRead!: boolean;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  // Associations
  public summary?: RequestSummary;
  public sharedByUser?: User;
  public sharedWithUser?: User;
}

SharedSummary.init(
  {
    sharedSummaryId: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
      field: 'shared_summary_id'
    },
    summaryId: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'summary_id',
      references: {
        model: 'request_summaries',
        key: 'summary_id'
      }
    },
    sharedBy: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'shared_by',
      references: {
        model: 'users',
        key: 'user_id'
      }
    },
    sharedWith: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'shared_with',
      references: {
        model: 'users',
        key: 'user_id'
      }
    },
    sharedAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      field: 'shared_at'
    },
    viewedAt: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'viewed_at'
    },
    isRead: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
      field: 'is_read'
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      field: 'created_at'
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      field: 'updated_at'
    }
  },
  {
    sequelize,
    tableName: 'shared_summaries',
    timestamps: true,
    underscored: true
  }
);

// Associations
SharedSummary.belongsTo(RequestSummary, {
  as: 'summary',
  foreignKey: 'summaryId',
  targetKey: 'summaryId'
});

SharedSummary.belongsTo(User, {
  as: 'sharedByUser',
  foreignKey: 'sharedBy',
  targetKey: 'userId'
});

SharedSummary.belongsTo(User, {
  as: 'sharedWithUser',
  foreignKey: 'sharedWith',
  targetKey: 'userId'
});

export default SharedSummary;

