AWSTemplateFormatVersion: '2010-09-09'
Description: 'Panchang Cron Job Lambda Function'

Parameters:
  MongoDBUri:
    Type: String
    Description: MongoDB connection string
    Default: "mongodb+srv://ankitdonhai:MGQEJ1DUF7V1VSds@cluster0.ad27ekx.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
  
  CronSchedule:
    Type: String
    Description: Cron schedule expression (UTC)
    Default: "cron(15 7 * * ? *)"  # 7:15 AM UTC daily

Resources:
  PanchangCronFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: panchang-cron
      Runtime: nodejs18.x
      Handler: cron-panchang.handler
      Code:
        ZipFile: |
          const axios = require('axios');
          const mongoose = require('mongoose');
          
          const PanchangSchema = new mongoose.Schema({
            date: { type: Date, default: Date.now },
            day: String,
            tithi: String,
            nakshatra: String,
            yog: String,
            karan: String,
            sunrise: String,
            sunset: String,
            vedic_sunrise: String,
            vedic_sunset: String,
          });
          
          const Panchang = mongoose.model('Panchang', PanchangSchema);
          
          exports.handler = async (event, context) => {
            try {
              console.log('Lambda function started at:', new Date().toISOString());
              
              const MONGODB_URI = process.env.MONGODB_URI;
              await mongoose.connect(MONGODB_URI, {
                useNewUrlParser: true,
                useUnifiedTopology: true,
              });
              
              const now = new Date();
              const requestBody = {
                day: now.getDate(),
                month: now.getMonth() + 1,
                year: now.getFullYear(),
                hour: 7,
                min: 15,
                lat: 28.6139,
                lon: 77.2090,
                tzone: 5.5
              };
              
              const response = await axios.post('https://backend.navambhaw.com/v2/alltimepanchang', requestBody);
              const data = response.data.message;
              const saved = await Panchang.create(data);
              
              await mongoose.connection.close();
              
              return {
                statusCode: 200,
                body: JSON.stringify({
                  success: true,
                  message: 'Panchang fetched and saved successfully',
                  panchangId: saved._id,
                  timestamp: now.toISOString()
                })
              };
            } catch (error) {
              console.error('Lambda function error:', error);
              if (mongoose.connection.readyState === 1) {
                await mongoose.connection.close();
              }
              return {
                statusCode: 500,
                body: JSON.stringify({
                  success: false,
                  error: error.message,
                  timestamp: new Date().toISOString()
                })
              };
            }
          };
      Environment:
        Variables:
          MONGODB_URI: !Ref MongoDBUri
      Timeout: 60
      MemorySize: 256
      Role: !GetAtt LambdaExecutionRole.Arn

  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

  EventBridgeRule:
    Type: AWS::Events::Rule
    Properties:
      Name: panchang-cron-rule
      Description: "Trigger panchang cron job daily at 7:15 AM UTC"
      ScheduleExpression: !Ref CronSchedule
      State: ENABLED
      Targets:
        - Arn: !GetAtt PanchangCronFunction.Arn
          Id: PanchangCronTarget

  EventBridgePermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref PanchangCronFunction
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt EventBridgeRule.Arn

Outputs:
  LambdaFunctionArn:
    Description: "ARN of the Lambda function"
    Value: !GetAtt PanchangCronFunction.Arn
    Export:
      Name: !Sub "${AWS::StackName}-LambdaArn"
  
  EventBridgeRuleArn:
    Description: "ARN of the EventBridge rule"
    Value: !GetAtt EventBridgeRule.Arn
    Export:
      Name: !Sub "${AWS::StackName}-RuleArn"
