import express from "express"
import dotenv from "dotenv"
import {prisma} from "../PrismaLab/prisma.js"
import { authMiddleware } from "../middleware/userauthMiddleware.js"
import { Octokit } from "octokit"
import {ethers} from "ethers"
dotenv.config()
const app = express()
const router = express.Router()


router.put("/checkCommit/:address",authMiddleware,async(req,res)=>{
  try{
    // First we will check the the last commit on github

    let userId = req.usersId
    let userAddress = req.params.address


    console.log("Value of address sent is " , userAddress)

    let access_token_usedata = await prisma.user.findFirst({
        where:{
          id:userId
        }
    })
    
    console.log("it is " , access_token_usedata.access_token)
    console.log("length of access token ", access_token_usedata.access_token.length)

    if(!access_token_usedata) return res.json({msg:"No User present"})

    const octokit = new Octokit({
      auth: access_token_usedata.access_token,
    });

    console.log("We are inside our mainFunction")
    
    
    let getDate = new Date(Date.now() - 24 * 60 * 60 * 1000);
    console.log(getDate)
    
    const { data } = await octokit.request('GET /user/repos', {
      since: getDate,
      headers: {
        'X-GitHub-Api-Version': '2026-03-10',
        accept:"application/vnd.github+json"
      }
    })

    console.log("data is " , data)

    console.log("we are after the commits")
    
    if(data.length === 0){
      console.log("no commits")
      return res.json({msg:false})
    }

    console.log("We are before the checkUserData")
    
    let todayDate = new Date().toISOString().slice(0,10);
    let checkUserData = await prisma.userCommitData.findFirst({
        where:{
           authorId:userId
        }
    })

    console.log("finded")



    console.log(process.env.PRIVATE_KEY)
    const wallet = new ethers.Wallet(process.env.PRIVATE_KEY)
    console.log("signer wallet:", wallet.address)

    let mysignDate = Math.floor(Date.now() / 1000)

    let setchecker = true;

    if(!checkUserData.lastCheckDate || checkUserData.lastCheckDate == "0"){
          setchecker = false;
    }

   const messageHash = ethers.solidityPackedKeccak256(
      ["address", "bool", "uint256"],
      [userAddress, setchecker, mysignDate]
    );

    const Signature = await wallet.signMessage(
      ethers.getBytes(messageHash)
    );

    console.log("checking Data")

        if(checkUserData.lastCheckDate == "0"){
          console.log({check:setchecker,timestamp:mysignDate,Sign:Signature})
          return res.json({check:setchecker,timestamp:mysignDate,Sign:Signature})
        }

        else if(checkUserData.lastCheckDate != todayDate){
           await prisma.userCommitData.update({
              where:{
                authorId:userId
              },
              data:{
                lastCheckDate:todayDate
              }
           })
           
        }

        console.log({check:setchecker,timestamp:mysignDate,Sign:Signature})
        return res.json({check:setchecker,timestamp:mysignDate,Sign:Signature})
        
    }

  catch(error){
    return res.json({msg:"Something went wrong while checking the commit "+ error})
  }
})

export default router