"""
Shares wasnt in yoyo migrations
"""

from yoyo import step

__depends__ = {"20230930_00_TNd34a-add-created-timestamp-to-favs"}

steps = [
    step(
        """
        CREATE TABLE IF NOT EXISTS public.shares (
            id serial4 NOT NULL,
            "name" varchar NOT NULL,
            description varchar NOT NULL,
            uploader int4 NULL,
            added timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
            CONSTRAINT shares_pkey PRIMARY KEY (id),
            CONSTRAINT shares_uploader_fkey FOREIGN KEY (uploader) REFERENCES public.account(id)
        );
        CREATE INDEX IF NOT EXISTS shares_added_idx ON public.shares USING btree (added);
        CREATE INDEX IF NOT EXISTS shares_uploader_idx ON public.shares USING btree (uploader);
        """
    ),
    step(
        """
        CREATE TABLE IF NOT EXISTS public.lookup_share_relationships (
            share_id int4 NOT NULL,
            service varchar NOT NULL,
            user_id varchar NOT NULL,
            CONSTRAINT lookup_share_relationships_pkey PRIMARY KEY (share_id, service, user_id),
            CONSTRAINT lookup_share_relationships_service_user_id_fkey FOREIGN KEY (service,user_id) REFERENCES public.lookup(service, id),
	        CONSTRAINT lookup_share_relationships_share_id_fkey FOREIGN KEY (share_id) REFERENCES public.shares(id)
        );
        """
    ),
    step(
        """
        CREATE TABLE IF NOT EXISTS public.file_share_relationships (
            share_id int4 NOT NULL,
            upload_url varchar NOT NULL,
            upload_id varchar NOT NULL,
            file_id int4 NULL,
            filename varchar NOT NULL,
            CONSTRAINT file_share_relationships_pkey PRIMARY KEY (share_id, upload_id),
            CONSTRAINT file_share_relationships_file_id_fkey FOREIGN KEY (file_id) REFERENCES public.files(id),
	        CONSTRAINT file_share_relationships_share_id_fkey FOREIGN KEY (share_id) REFERENCES public.shares(id)
        );
        """
    ),
    step("""DROP INDEX IF EXISTS file_share_id_idx;"""),
]

"""
Use this to remove duplicates from file_server_relationships

DELETE FROM public.file_server_relationships T1
using public.file_server_relationships T2
WHERE  T1.ctid > T2.ctid AND  T1.file_id = T2.file_id AND T1.remote_path = T2.remote_path
"""
