package pl.polskalokalnie.config;

import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class SchemaFixer {

    @Bean
    ApplicationRunner ensureViewsCountColumn(JdbcTemplate jdbcTemplate) {
        return args -> {
            jdbcTemplate.execute(
                "ALTER TABLE property_listings ADD COLUMN IF NOT EXISTS views_count BIGINT NOT NULL DEFAULT 0"
            );
            jdbcTemplate.execute(
                "ALTER TABLE app_users ADD COLUMN IF NOT EXISTS address VARCHAR(255)"
            );
            jdbcTemplate.execute(
                "ALTER TABLE app_users ADD COLUMN IF NOT EXISTS contact_preference VARCHAR(20)"
            );
            jdbcTemplate.execute(
                "UPDATE app_users SET contact_preference = 'EMAIL_AND_PHONE' WHERE contact_preference IS NULL"
            );
            jdbcTemplate.execute(
                "ALTER TABLE app_users ALTER COLUMN contact_preference SET DEFAULT 'EMAIL_AND_PHONE'"
            );
            jdbcTemplate.execute(
                "ALTER TABLE app_users ALTER COLUMN contact_preference SET NOT NULL"
            );
            jdbcTemplate.execute(
                "ALTER TABLE app_users ADD COLUMN IF NOT EXISTS preferred_language VARCHAR(10)"
            );
            jdbcTemplate.execute(
                "UPDATE app_users SET preferred_language = 'PL' WHERE preferred_language IS NULL"
            );
            jdbcTemplate.execute(
                "ALTER TABLE app_users ALTER COLUMN preferred_language SET DEFAULT 'PL'"
            );
            jdbcTemplate.execute(
                "ALTER TABLE app_users ALTER COLUMN preferred_language SET NOT NULL"
            );
            jdbcTemplate.execute(
                "ALTER TABLE IF EXISTS listing_report_attachments ADD COLUMN IF NOT EXISTS file_type VARCHAR(120)"
            );
            jdbcTemplate.execute(
                "ALTER TABLE IF EXISTS listing_report_attachments ADD COLUMN IF NOT EXISTS data_url TEXT"
            );

            // Hibernate (ddl-auto=update) nie aktualizuje CHECK constraintu enuma po dodaniu nowej wartosci.
            // Odtwarzamy go tak, aby dopuszczal status PAUSED (wstrzymane ogloszenie uzytkownika).
            jdbcTemplate.execute(
                "ALTER TABLE property_listings DROP CONSTRAINT IF EXISTS property_listings_status_check"
            );
            jdbcTemplate.execute(
                "ALTER TABLE property_listings ADD CONSTRAINT property_listings_status_check "
                + "CHECK (status IN ('PENDING','APPROVED','REJECTED','PAUSED'))"
            );

            String dataUrlType = jdbcTemplate.query(
                "SELECT data_type FROM information_schema.columns WHERE table_name = 'listing_report_attachments' AND column_name = 'data_url'",
                rs -> rs.next() ? rs.getString(1) : null
            );

            if ("oid".equalsIgnoreCase(dataUrlType)) {
            jdbcTemplate.execute("ALTER TABLE listing_report_attachments ADD COLUMN IF NOT EXISTS data_url_text TEXT");
            jdbcTemplate.execute(
                "UPDATE listing_report_attachments " +
                "SET data_url_text = CASE WHEN data_url IS NULL THEN NULL ELSE convert_from(lo_get(data_url), 'UTF8') END"
            );
            jdbcTemplate.execute(
                "DO $$ " +
                "BEGIN " +
                "  IF EXISTS (SELECT 1 FROM listing_report_attachments WHERE data_url IS NOT NULL) THEN " +
                "    PERFORM lo_unlink(data_url) FROM listing_report_attachments WHERE data_url IS NOT NULL; " +
                "  END IF; " +
                "END $$"
            );
            jdbcTemplate.execute("ALTER TABLE listing_report_attachments DROP COLUMN data_url");
            jdbcTemplate.execute("ALTER TABLE listing_report_attachments RENAME COLUMN data_url_text TO data_url");
            }
        };
    }
}
