import BaseSchema from '@ioc:Adonis/Lucid/Schema';

export default class LinkDocumentsLicences extends BaseSchema {
    protected tableName = 'link_documents_licences';

    public async up() {
        this.schema.createTable(this.tableName, (table) => {
            table.integer('licence_id').index('link_documents_licences_licence_id_index').notNullable();
            table
                .foreign('licence_id', 'link_documents_licences_licence_id_foreign')
                .references('id')
                .inTable('document_licences')
                .onDelete('NO ACTION') // don't delete this when license is deleted
                .onUpdate('NO ACTION');
            // table.index('licence_id', 'link_documents_licences_licence_id_index')
            table.integer('document_id').index('link_documents_licences_document_id_index').notNullable();
            table
            .foreign('document_id', 'link_documents_licences_document_id_foreign')
            .references('id')
            .inTable('documents')
            .onDelete('CASCADE') // delete this when document is deleted
            .onUpdate(' CASCADE');
            // table.index('licence_id', 'link_documents_licences_document_id_index')           
            table.primary(['licence_id', 'document_id']);
        });
    }

    public async down() {
        this.schema.dropTable(this.tableName);
    }
}

// -- Table: link_documents_licences
// CREATE TABLE IF NOT EXISTS link_documents_licences
// (
//     licence_id integer NOT NULL,
//     document_id integer NOT NULL,
//     role character varying(255) NOT NULL DEFAULT 'other'::character varying,
//     CONSTRAINT link_documents_licences_pkey PRIMARY KEY (licence_id, document_id),
//     CONSTRAINT link_documents_licences_document_id_foreign FOREIGN KEY (document_id)
//         REFERENCES documents (id) MATCH SIMPLE
//         ON UPDATE CASCADE
//         ON DELETE CASCADE,
//     CONSTRAINT link_documents_licences_licence_id_foreign FOREIGN KEY (licence_id)
//         REFERENCES document_licences (id) MATCH SIMPLE
//         ON UPDATE NO ACTION
//         ON DELETE NO ACTION,
// )
// ALTER TABLE IF EXISTS link_documents_licences
//     OWNER to tethys_admin;
// REVOKE ALL ON TABLE link_documents_licences FROM tethys_app;
// GRANT ALL ON TABLE link_documents_licences TO tethys_admin;
// GRANT DELETE, INSERT, SELECT, UPDATE ON TABLE link_documents_licences TO tethys_app;

// -- Index: link_documents_licences_document_id_index
// CREATE INDEX IF NOT EXISTS link_documents_licences_document_id_index
//     ON link_documents_licences USING btree
//     (document_id ASC);
// -- Index: link_documents_licences_licence_id_index
// CREATE INDEX IF NOT EXISTS link_documents_licences_licence_id_index
//     ON link_documents_licences USING btree
//     (licence_id ASC);
