-- Flyway Migration: V2.2.0.4
-- Purpose: Refactor LIBRARY_UNMATCHED_PATHS to LIBRARY_IGNORED_PATHS with proper entity structure
--          Add IGNORED_PATH and IGNORED_PATH_SOURCE tables using single-table inheritance
--          Migrate existing unmatched paths as plugin-sourced ignored paths (system-generated)

--- Create sequence for primary key generation
CREATE SEQUENCE IGNORED_PATH_SEQ
    INCREMENT BY 50;

CREATE SEQUENCE IGNORED_PATH_SOURCE_SEQ
    INCREMENT BY 50;

-- Create the IGNORED_PATH_SOURCE table (single-table inheritance)
CREATE TABLE IGNORED_PATH_SOURCE
(
    ID      BIGINT      NOT NULL PRIMARY KEY,
    DTYPE   VARCHAR(31) NOT NULL, -- Discriminator column for inheritance
    USER_ID BIGINT,               -- For IgnoredPathUserSource
    CONSTRAINT FK_IGNORED_PATH_SOURCE_USER
        FOREIGN KEY (USER_ID) REFERENCES USERS (ID)
            ON DELETE CASCADE
);

-- Create junction table for plugin sources (many-to-many relationship)
CREATE TABLE IGNORED_PATH_SOURCE_PLUGINS
(
    IGNORED_PATH_PLUGIN_SOURCE_ID BIGINT       NOT NULL,
    PLUGINS_PLUGIN_ID             VARCHAR(255) NOT NULL,
    CONSTRAINT FK_IGNORED_PATH_SOURCE_PLUGINS_SOURCE
        FOREIGN KEY (IGNORED_PATH_PLUGIN_SOURCE_ID) REFERENCES IGNORED_PATH_SOURCE (ID)
            ON DELETE CASCADE,
    CONSTRAINT FK_IGNORED_PATH_SOURCE_PLUGINS_PLUGIN
        FOREIGN KEY (PLUGINS_PLUGIN_ID) REFERENCES PLUGIN_MANAGEMENT_ENTRY (PLUGIN_ID)
            ON DELETE CASCADE
);

-- Create IGNORED_PATH table
CREATE TABLE IGNORED_PATH
(
    ID        BIGINT        NOT NULL PRIMARY KEY,
    PATH      VARCHAR(1024) NOT NULL
        CONSTRAINT UK_IGNORED_PATH_PATH
            UNIQUE,
    SOURCE_ID BIGINT        NOT NULL,
    CONSTRAINT FK_IGNORED_PATH_SOURCE
        FOREIGN KEY (SOURCE_ID) REFERENCES IGNORED_PATH_SOURCE (ID)
            ON DELETE CASCADE,
    CONSTRAINT CK_IGNORED_PATH_PATH_NOT_EMPTY
        CHECK (TRIM(PATH) <> '')
);

-- Create LIBRARY_IGNORED_PATHS junction table
CREATE TABLE LIBRARY_IGNORED_PATHS
(
    LIBRARY_ID       BIGINT NOT NULL,
    IGNORED_PATHS_ID BIGINT NOT NULL,
    CONSTRAINT UK_LIBRARY_IGNORED_PATHS_COMPOSITE
        UNIQUE (LIBRARY_ID, IGNORED_PATHS_ID),
    CONSTRAINT FK_LIBRARY_IGNORED_PATHS_LIBRARY
        FOREIGN KEY (LIBRARY_ID) REFERENCES LIBRARY (ID)
            ON DELETE CASCADE,
    CONSTRAINT FK_LIBRARY_IGNORED_PATHS_IGNORED_PATH
        FOREIGN KEY (IGNORED_PATHS_ID) REFERENCES IGNORED_PATH (ID)
            ON DELETE CASCADE
);

-- Create indexes for better query performance
CREATE INDEX IDX_LIBRARY_IGNORED_PATHS_LIBRARY_ID ON LIBRARY_IGNORED_PATHS (LIBRARY_ID);
CREATE INDEX IDX_IGNORED_PATH_SOURCE_ID ON IGNORED_PATH (SOURCE_ID);
CREATE INDEX IDX_IGNORED_PATH_SOURCE_USER_ID ON IGNORED_PATH_SOURCE (USER_ID);
CREATE INDEX IDX_IGNORED_PATH_SOURCE_PLUGINS ON IGNORED_PATH_SOURCE_PLUGINS (IGNORED_PATH_PLUGIN_SOURCE_ID);

-- Drop the old LIBRARY_UNMATCHED_PATHS table
DROP TABLE LIBRARY_UNMATCHED_PATHS;

