const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient();
const { v4: uuidv4 } = require('uuid');

const TABLE_NAME = process.env.TABLE_NAME;

// CORS headers
const headers = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': process.env.CORS_ORIGIN || '*',
  'Access-Control-Allow-Headers': 'Content-Type,Authorization',
  'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS'
};

// Helper function to create response
const createResponse = (statusCode, body) => ({
  statusCode,
  headers,
  body: JSON.stringify(body)
});

// GET all filaments or filter by query params
const getFilaments = async (event) => {
  try {
    const queryParams = event.queryStringParameters || {};
    
    let params = {
      TableName: TABLE_NAME
    };

    // If filtering by brand, type, or status, use the appropriate index
    if (queryParams.brand) {
      params = {
        ...params,
        IndexName: 'brand-index',
        KeyConditionExpression: 'brand = :brand',
        ExpressionAttributeValues: {
          ':brand': queryParams.brand
        }
      };
      const result = await dynamodb.query(params).promise();
      return createResponse(200, result.Items);
    } else if (queryParams.tip) {
      params = {
        ...params,
        IndexName: 'tip-index',
        KeyConditionExpression: 'tip = :tip',
        ExpressionAttributeValues: {
          ':tip': queryParams.tip
        }
      };
      const result = await dynamodb.query(params).promise();
      return createResponse(200, result.Items);
    } else if (queryParams.status) {
      params = {
        ...params,
        IndexName: 'status-index',
        KeyConditionExpression: 'status = :status',
        ExpressionAttributeValues: {
          ':status': queryParams.status
        }
      };
      const result = await dynamodb.query(params).promise();
      return createResponse(200, result.Items);
    }

    // Get all items
    const result = await dynamodb.scan(params).promise();
    return createResponse(200, result.Items);
  } catch (error) {
    console.error('Error getting filaments:', error);
    return createResponse(500, { error: 'Failed to fetch filaments' });
  }
};

// GET single filament by ID
const getFilament = async (event) => {
  try {
    const { id } = event.pathParameters;
    
    const params = {
      TableName: TABLE_NAME,
      Key: { id }
    };

    const result = await dynamodb.get(params).promise();
    
    if (!result.Item) {
      return createResponse(404, { error: 'Filament not found' });
    }

    return createResponse(200, result.Item);
  } catch (error) {
    console.error('Error getting filament:', error);
    return createResponse(500, { error: 'Failed to fetch filament' });
  }
};

// POST - Create new filament
const createFilament = async (event) => {
  try {
    const body = JSON.parse(event.body);
    const timestamp = new Date().toISOString();
    
    // Determine status based on vakum and otvoreno fields
    let status = 'new';
    if (body.otvoreno && body.otvoreno.toLowerCase().includes('otvorena')) {
      status = 'opened';
    } else if (body.refill && body.refill.toLowerCase() === 'da') {
      status = 'refill';
    }
    
    const item = {
      id: uuidv4(),
      ...body,
      status,
      createdAt: timestamp,
      updatedAt: timestamp
    };

    const params = {
      TableName: TABLE_NAME,
      Item: item
    };

    await dynamodb.put(params).promise();
    return createResponse(201, item);
  } catch (error) {
    console.error('Error creating filament:', error);
    return createResponse(500, { error: 'Failed to create filament' });
  }
};

// PUT - Update filament
const updateFilament = async (event) => {
  try {
    const { id } = event.pathParameters;
    const body = JSON.parse(event.body);
    const timestamp = new Date().toISOString();
    
    // Determine status based on vakum and otvoreno fields
    let status = 'new';
    if (body.otvoreno && body.otvoreno.toLowerCase().includes('otvorena')) {
      status = 'opened';
    } else if (body.refill && body.refill.toLowerCase() === 'da') {
      status = 'refill';
    }

    const params = {
      TableName: TABLE_NAME,
      Key: { id },
      UpdateExpression: `SET 
        brand = :brand,
        tip = :tip,
        finish = :finish,
        boja = :boja,
        refill = :refill,
        vakum = :vakum,
        otvoreno = :otvoreno,
        kolicina = :kolicina,
        cena = :cena,
        #status = :status,
        updatedAt = :updatedAt`,
      ExpressionAttributeNames: {
        '#status': 'status'
      },
      ExpressionAttributeValues: {
        ':brand': body.brand,
        ':tip': body.tip,
        ':finish': body.finish,
        ':boja': body.boja,
        ':refill': body.refill,
        ':vakum': body.vakum,
        ':otvoreno': body.otvoreno,
        ':kolicina': body.kolicina,
        ':cena': body.cena,
        ':status': status,
        ':updatedAt': timestamp
      },
      ReturnValues: 'ALL_NEW'
    };

    const result = await dynamodb.update(params).promise();
    return createResponse(200, result.Attributes);
  } catch (error) {
    console.error('Error updating filament:', error);
    return createResponse(500, { error: 'Failed to update filament' });
  }
};

// DELETE filament
const deleteFilament = async (event) => {
  try {
    const { id } = event.pathParameters;
    
    const params = {
      TableName: TABLE_NAME,
      Key: { id }
    };

    await dynamodb.delete(params).promise();
    return createResponse(200, { message: 'Filament deleted successfully' });
  } catch (error) {
    console.error('Error deleting filament:', error);
    return createResponse(500, { error: 'Failed to delete filament' });
  }
};

// Main handler
exports.handler = async (event) => {
  const { httpMethod, resource } = event;

  // Handle CORS preflight
  if (httpMethod === 'OPTIONS') {
    return createResponse(200, {});
  }

  // Route requests
  if (resource === '/filaments' && httpMethod === 'GET') {
    return getFilaments(event);
  } else if (resource === '/filaments' && httpMethod === 'POST') {
    return createFilament(event);
  } else if (resource === '/filaments/{id}' && httpMethod === 'GET') {
    return getFilament(event);
  } else if (resource === '/filaments/{id}' && httpMethod === 'PUT') {
    return updateFilament(event);
  } else if (resource === '/filaments/{id}' && httpMethod === 'DELETE') {
    return deleteFilament(event);
  }

  return createResponse(404, { error: 'Not found' });
};