#!/bin/bash
# Fix database permissions for skyartapp user

echo "🔐 Fixing database permissions..."

sudo -u postgres psql -d skyartshop <<EOF
-- Grant all privileges on schema
GRANT ALL ON SCHEMA public TO skyartapp;

-- Grant all privileges on all tables
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO skyartapp;

-- Grant all privileges on all sequences
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO skyartapp;

-- Change ownership of all tables to skyartapp
DO \$\$
DECLARE
    r RECORD;
BEGIN
    FOR r IN SELECT tablename FROM pg_tables WHERE schemaname = 'public'
    LOOP
        EXECUTE 'ALTER TABLE ' || quote_ident(r.tablename) || ' OWNER TO skyartapp';
    END LOOP;
END \$\$;

-- Change ownership of all sequences
DO \$\$
DECLARE
    r RECORD;
BEGIN
    FOR r IN SELECT sequence_name FROM information_schema.sequences WHERE sequence_schema = 'public'
    LOOP
        EXECUTE 'ALTER SEQUENCE ' || quote_ident(r.sequence_name) || ' OWNER TO skyartapp';
    END LOOP;
END \$\$;

\echo '✅ Permissions fixed!'
EOF

echo "✅ Done! Now you can run: node apply-db-fixes.js"
