-- Shared drive import mode and project-level dedup for Google Workspace migrations.
ALTER TABLE migration_projects
    ADD COLUMN shared_drive_mode TEXT NOT NULL DEFAULT 'auto';

ALTER TABLE migration_projects
    ADD CONSTRAINT migration_projects_shared_drive_mode_check
    CHECK (shared_drive_mode IN ('auto', 'manual'));

CREATE TABLE migration_shared_drives (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    project_id UUID NOT NULL REFERENCES migration_projects(id) ON DELETE CASCADE,
    drive_id TEXT NOT NULL,
    name TEXT NOT NULL DEFAULT '',
    status TEXT NOT NULL DEFAULT 'pending',
    discovered_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(project_id, drive_id),
    CONSTRAINT migration_shared_drives_status_check
        CHECK (status IN ('pending', 'approved', 'rejected'))
);

CREATE INDEX idx_migration_shared_drives_project_status
    ON migration_shared_drives(project_id, status);

-- Project-level dedup: one import per shared-drive file across all users in a project.
CREATE TABLE migration_shared_drive_items (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    project_id UUID NOT NULL REFERENCES migration_projects(id) ON DELETE CASCADE,
    drive_id TEXT NOT NULL,
    source_id TEXT NOT NULL,
    rel_path TEXT NOT NULL DEFAULT '',
    imported_by_job_id UUID REFERENCES migration_jobs(id) ON DELETE SET NULL,
    imported_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(project_id, drive_id, source_id)
);

CREATE INDEX idx_migration_shared_drive_items_project
    ON migration_shared_drive_items(project_id, drive_id);
