
const { empty } = require("../Helpers/Common");
const sequelize = require("../config/dbconnection");
const Sequelize = require('sequelize')
const Documents = sequelize.define('documents', {
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    name: { type: Sequelize.CHAR, allowNull: false },
    document_type: { type: Sequelize.TINYINT, allowNull: false,defaultValue:1 },
    attachment: { type: Sequelize.CHAR, allowNull: true,defaultValue:null },
    content: { type: Sequelize.TEXT, allowNull: true, },
    added_by: { type: Sequelize.INTEGER, allowNull: false },
    timestamp: { type: Sequelize.INTEGER, allowNull: false },
    status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
    updated_on: { type: Sequelize.INTEGER, allowNull: false },
  },{timestamps:false}
)

const getAllRequestedDocuments=async(type)=>{
    try {
        if(!empty(type)){
            let result = await sequelize.query(`
             SELECT d.*
             FROM documents AS d
             WHERE d.status = 1 AND d.document_type = ${type}
             ORDER BY d.id DESC;
            `)
           
            if(!empty(result)){
                if (result[0].length > 0) {
                    data = result[0];
                  }
                  return data;
            }else{
                return false
            }
        }
    } catch (error) {
        console.log(error)
    }
}
const getAllDocumentIds =async(documentType,ids,partnerId,teamId)=>{
    try {
        let result = await sequelize.query(`
        SELECT d.*,
        pd.id AS partner_document_id,
        pd.file_name AS partner_document_value,
       pd.issue_date AS partner_document_issue_date,
       pd.expiry_date AS partner_document_expiry_date
        FROM documents d
      LEFT JOIN partner_documents pd ON pd.document_id = d.id AND pd.partner_id = ${partnerId} AND pd.onboarding = 1
      LEFT JOIN team_documents td ON td.document_id = d.id AND td.team_id = ${teamId} AND td.onboarding = 1
      WHERE d.status = 1
      AND d.document_type =  ${documentType}
      AND d.id IN (:ids)
      ORDER BY FIELD(d.id,  ${ids});
`)
if(result){
    if(!empty(result)){
        if (result[0].length > 0) {
            data = result[0];
          }
          return data;
    }else{
        return false
    }
}
    } catch (error) {
        console.log(error)
    }
}
const addDocument=async(data)=>{
    try {
       let result = await Documents.create(data)
       return result
    } catch (error) {
        console.log(error)
    }
}
module.exports={
    getAllRequestedDocuments,
    getAllDocumentIds,
    addDocument,
}