#!/bin/bash
# Script to update database via AWS

# Get RDS endpoint from AWS
echo "Getting RDS instance information..."
RDS_ENDPOINT=$(aws rds describe-db-instances --db-instance-identifier filamenteka --query 'DBInstances[0].Endpoint.Address' --output text)
RDS_PORT=$(aws rds describe-db-instances --db-instance-identifier filamenteka --query 'DBInstances[0].Endpoint.Port' --output text)

# Get database credentials from Secrets Manager
echo "Getting database credentials from AWS Secrets Manager..."
DB_CREDS=$(aws secretsmanager get-secret-value --secret-id filamenteka-db-credentials --query 'SecretString' --output text)
DB_USER=$(echo $DB_CREDS | jq -r '.username')
DB_PASS=$(echo $DB_CREDS | jq -r '.password')
DB_NAME=$(echo $DB_CREDS | jq -r '.database')

# Construct database URL
DATABASE_URL="postgresql://${DB_USER}:${DB_PASS}@${RDS_ENDPOINT}:${RDS_PORT}/${DB_NAME}"

echo "Connecting to database..."
echo ""

# Run the SQL script
psql "$DATABASE_URL" << 'EOF'
-- Add 1 refill for each color as PLA Basic filaments

-- First show what colors we have
\echo 'Existing colors:'
SELECT name, hex FROM colors ORDER BY name;
\echo ''

-- Insert PLA Basic filaments with 1 refill for each color that doesn't already have one
\echo 'Adding PLA Basic filaments with 1 refill for each color...'
INSERT INTO filaments (tip, finish, boja, boja_hex, refill, vakum, otvoreno, kolicina, cena)
SELECT 
    'PLA' as tip,
    'Basic' as finish,
    c.name as boja,
    c.hex as boja_hex,
    '1' as refill,
    '0 vakuum' as vakum,
    '0 otvorena' as otvoreno,
    1 as kolicina,
    '3999' as cena
FROM colors c
WHERE NOT EXISTS (
    SELECT 1 FROM filaments f 
    WHERE f.tip = 'PLA' 
    AND f.finish = 'Basic' 
    AND f.boja = c.name
)
ON CONFLICT DO NOTHING;

-- Update any existing PLA Basic filaments to have 1 refill if they don't have any
UPDATE filaments
SET refill = '1'
WHERE tip = 'PLA' 
AND finish = 'Basic'
AND (refill IS NULL OR refill = '0' OR refill = '');

-- Show summary
\echo ''
\echo 'Summary:'
SELECT 
    'Total PLA Basic filaments with refills' as description,
    COUNT(*) as count 
FROM filaments 
WHERE tip = 'PLA' 
AND finish = 'Basic' 
AND refill = '1';

-- Show all PLA Basic filaments
\echo ''
\echo 'All PLA Basic filaments:'
SELECT 
    boja as color,
    refill,
    vakum as vacuum,
    otvoreno as opened,
    kolicina as quantity,
    cena as price
FROM filaments 
WHERE tip = 'PLA' 
AND finish = 'Basic'
ORDER BY boja;
EOF

echo ""
echo "Database update completed!"