import { DataTypes, Model, Optional } from "sequelize";
import Joi from "joi";
import sequelize from "../middlewears/sequelize";

export interface IShop {
  id: number;
  name: string;
  location: string;
  number: string;
  shopkeeperIds: number[]; // Array of user IDs
  shopkeeperNames: string[]; // Array of user names
  isDeleted: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}

interface IShopCreationAttributes
  extends Optional<IShop, "id" | "createdAt" | "updatedAt" | "isDeleted" | "shopkeeperIds" | "shopkeeperNames"> {}

class ShopModel extends Model<IShop, IShopCreationAttributes> implements IShop {
  public id!: number;
  public name!: string;
  public location!: string;
  public number!: string;
  public shopkeeperIds!: number[];
  public shopkeeperNames!: string[];
  public isDeleted!: boolean;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

ShopModel.init(
  {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    name: { type: DataTypes.STRING, allowNull: false },
    location: { type: DataTypes.STRING, allowNull: false },
    number: { type: DataTypes.STRING, allowNull: false },
    shopkeeperIds: { 
      type: DataTypes.JSON, 
      allowNull: false,
      defaultValue: []
    },
    shopkeeperNames: { 
      type: DataTypes.JSON, 
      allowNull: false,
      defaultValue: []
    },
    isDeleted: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
  },
  {
    sequelize,
    tableName: "shops",
  }
);

const shopValidationSchema = Joi.object({
  name: Joi.string().min(1).max(100).required(),
  location: Joi.string().min(1).max(255).required(),
  number: Joi.string().min(7).max(15).required(),
  shopkeeperIds: Joi.array().items(Joi.number().integer().positive()).default([]),
  shopkeeperNames: Joi.array().items(Joi.string().min(1).max(100)).default([]),
  isDeleted: Joi.boolean().optional(),
});

export { ShopModel, shopValidationSchema };
