import { Model, model, Schema } from "mongoose";
import { IGasStationPayment } from "../interfaces/models/gasStationPaymentInterface";

const GasStationPaymentSchema = new Schema<IGasStationPayment>(
  {
    receiptNumber: {
      type: String,
      required: true,
      trim: true,
      unique: true,
      index: true,
    },
    payerId: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: true,
      index: true,
    },
    gasStationId: {
      type: Schema.Types.ObjectId,
      ref: "GasStation",
      required: true,
      index: true,
    },
    stationOwnerId: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: true,
      index: true,
    },
    amountCents: {
      type: Number,
      required: true,
      min: 1,
    },
    currency: {
      type: String,
      default: "usd",
      trim: true,
      lowercase: true,
    },
    status: {
      type: String,
      enum: ["pending", "completed", "failed", "refunded"],
      default: "pending",
      required: true,
      index: true,
    },
    note: {
      type: String,
      trim: true,
      maxlength: 255,
      default: null,
    },
    tripId: {
      type: Schema.Types.ObjectId,
      ref: "trips",
      default: null,
    },
    idempotencyKey: {
      type: String,
      required: true,
      trim: true,
    },
    payerWalletTxId: {
      type: Schema.Types.ObjectId,
      ref: "WalletTransaction",
      default: null,
    },
    payeeWalletTxId: {
      type: Schema.Types.ObjectId,
      ref: "WalletTransaction",
      default: null,
    },
    receiptEmailedAt: {
      type: Date,
      default: null,
    },
    paidAt: {
      type: Date,
      default: null,
    },
    failureReason: {
      type: String,
      trim: true,
      default: null,
    },
  },
  { timestamps: true },
);

GasStationPaymentSchema.index(
  { payerId: 1, idempotencyKey: 1 },
  { unique: true },
);
GasStationPaymentSchema.index({ stationOwnerId: 1, createdAt: -1 });
GasStationPaymentSchema.index({ payerId: 1, createdAt: -1 });

const GasStationPaymentModel: Model<IGasStationPayment> =
  model<IGasStationPayment>("GasStationPayment", GasStationPaymentSchema);

export default GasStationPaymentModel;
