# Install Sinatra: gem install sinatra
require_relative "initialize_database"
require_relative "database_queries"
require_relative "cryptography"
require_relative "tokens"


require 'sinatra'
require 'json'
require 'sqlite3'
require 'jwt'

TOKEN_SECRET = 'WChX-tQWbGbj_pGJQREoFAZGC9JWh58KSk8O7KPj-P8Nd-J88g3eSFDVuNe6zddj0ZB3yxjm_IuPNPyLhiSnxlWHImqXR6ajh3OzrzYm0bNb3f5C4IAScphyEdAfYGMcM-HvYOXxxxp5u5mryfiV3JH1CTqL1CzGyO8df7zUpRKXEXZ5SKmUvhfLU0XKCR_28FAZUgPCAi3GywkDDsH0by68j33BU5cnMT8KiEkHOX4wVUVDQc85_AuE7fN3ji_WkhnDCSLXU9dBCcXM3ziFFeX0RbvIRDG0vKdzwt4TOr4Jws7NP9w11GrUGDFKARZqvT7FTxwxO3MM-mmjb2xyGg'

set :public_folder, DATA_LOCATION + FILE_STORAGE_LOCATION

#puts generate_random_string(256)


#
#token = JWT.encode payload, hmac_secret, 'HS256'
##puts token
#
#begin
#  decoded_token = JWT.decode token, hmac_secret, true, { algorithm: 'HS256' }
#  puts "Token is valid!"
#  puts "Decoded token: #{decoded_token}"
#
#  puts data_value = decoded_token.first['data']
#  puts test_value = decoded_token.first['test']
#rescue JWT::DecodeError
#  puts "Invalid token or signature!"
#end

#puts decoded_token

initialize_database

post '/auth/login' do
  content_type :json
  
  username = params[:username]
  password = params[:password]

  unless check_if_user_exists username
    status 401
    
    return { reply: "Unuthorized Access" }.to_json
  end

  user_id = get_user_id username

  unless check_password_for_user(user_id, password)
    status 401
    
    return { reply: "Unuthorized Access" }.to_json
  end

  reauthJWT = get_reauth_jwt user_id

  return {token: reauthJWT}.to_json
end

post '/auth/reauthenticate' do
  content_type :json

  authorization_header = request.env['HTTP_AUTHORIZATION']

  unless authorization_header && authorization_header.match(/^Bearer (.+)/)
    status 401
    return { reply: 'Unauthorized Access. Token missing or invalid.' }.to_json
  end

  reauth_token = Regexp.last_match(1)

  begin
    # Verify the token using the secret key
    decoded_token = JWT.decode(reauth_token, TOKEN_SECRET, true, algorithm: 'HS256')

    # At this point, the token is valid
    # You can access the claims inside the 'decoded_token' variable
    
    uid = decoded_token.first['uid']
    
    # Your reauthentication logic here...

    # Return a response (replace with your own logic)
    { jwt: get_jwt(uid) }.to_json
  rescue JWT::DecodeError
    status 401
    return { reply: 'Unauthorized Access. Invalid token.' }.to_json
  end
end

post '/upload' do

  authorization_header = request.env['HTTP_AUTHORIZATION']

  unless authorization_header && authorization_header.match(/^Bearer (.+)/)
    status 401
    return { reply: 'Unauthorized Access. Token missing or invalid.' }.to_json
  end

  token = Regexp.last_match(1)

  begin
    # Verify the token using the secret key
    decoded_token = JWT.decode(token, TOKEN_SECRET, true, algorithm: 'HS256')

    unless decoded_token.first['claims'].include? 'is_machine'
      status 401
      return { reply: 'Unauthorized Access.' }.to_json
    end
  
    # Access the uploaded file through the params hash
    file = params[:file]
      
    # Save the file to the 'uploads' folder
    path =  "#{DATA_LOCATION}#{FILE_STORAGE_LOCATION}/example.txt"
    File.open(path, 'wb') do |f|
      f.write(file[:tempfile].read)
    end
  
    "File uploaded successfully: #{file[:filename]}"
  rescue JWT::DecodeError
    status 401
    return { reply: 'Unauthorized Access. Invalid token.' }.to_json
  end
end

# Run the application
# ruby your_file_name.rb
